创建对象
1.工厂模式
例子:
function createPerson(name , age , job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name) ; }; return o; } var person1 = createPerson("Nichilos","29","Soft Engineer"); var person2 = createPerson("Grey","27","Doctor");
2.构造函数模式
构造函数与其他函数唯一的区别就是调用它们的方式不同
例子
function Person(name , age , job){ this.name = name; this.age = age; this.job = job; this.sayName = function(){ alert(this.name); }; } //当做构造函数调用 var person1 = new Person("Nicholos","29","Software Engineer"); person1.sayName();//"Nicholos" //作为普通函数调用 Person("Grey","29","Software Engineer");//添加到window window.sayName();//"Grey" //在另一个对象的作用域中调用 var o = new Object(); Person.call(o,"Kreis","24","Nurse"); o.sayName();//"Kreis"
特点1:没有显示的创建对象;
特点2:直接将属性和方法赋给了this对象;
特点3:没有return语句。
存在的问题:
alert(person1.sayName==person2.sayName); //false
将函数定义转移到构造函数之外
function Person(name , age ,job){ this.name = name; this.age = age; this.job = job; this.sayName = sayName; } function sayName(){ alert(this.name); } var person1 = new Person("Nichilos","29","Soft Engineer"); var person2 = new Person("Grey","27","Doctor");
3.原型模式
function Person(){ } Person.prototype.name = "Nicholos"; Person.prototype.age = "29"; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function(){ alert(this.name); }; var person1 = new Person(); person1.name = "Grey"; alert(person1.name);//"Grey" person1.sayName();// "Nicholos" var person2 = new Person(); alert(person2.name);//"Nicholos"" alert(person1.sayName == person2.sayName);//ture
4.组合使用构造函数和原型函数模式
function Person(name , age ,job){ this.name = name; this.age = age; this.job = job; this.friends = ["Shelby","Court"];} Person.prototype = { constructor : Person, sayName : function(){ alert(this.name); } } var person1 = new Person("Nichilos","29","Soft Engineer"); var person2 = new Person("Grey","27","Doctor"); person1.friends.push("Van"); alert(person1.friends);//"Shelby","Court","Van" alert(person2.friends);//"Shelby","Court" alert(person1.friends == person2.friends);//false alert(person1.sayName == person2.sayName);//true
时间: 2024-10-18 00:46:00