关于JavaScript创建对象的方式:
1、工厂模式
1 function createPerson(name, age, job){ 2 var o = new Object(); 3 o.name = name; 4 o.age = age; 5 o.job = job; 6 o.sayName = function(){ 7 alert(this.name); 8 }; 9 return o; 10 } 11 var person1 = createPerson("Nicholas", 29, "Software Engineer"); 12 var person2 = createPerson("Greg", 27, "Doctor");
缺点:没有体现出面向对象的思想
2、构造函数模式
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.sayName = function(){ 6 alert(this.name); 7 }; 8 } 9 var person1 = new Person("Nicholas", 29, "Software Engineer"); 10 var person2 = new Person("Greg", 27, "Doctor"); 11 person1.sayName(); //"Nicholas" 12 person2.sayName(); //"Greg"
缺点:1、构造函数中的每个方法在创建实例时都要重新创建一遍,即
this.sayName = new Function(){alert(this.name);};
alert(person1.sayName == person2.sayName); //false
3、原型模式
1 function Person(){ 2 } 3 Person.prototype.name = "Nicholas"; 4 Person.prototype.age = 29; 5 Person.prototype.job = "Software Engineer"; 6 Person.prototype.sayName = function(){ 7 alert(this.name); 8 }; 9 var person1 = new Person(); 10 person1.sayName(); //"Nicholas" 11 12 var person2 = new Person(); 13 person2.sayName(); //"Nicholas" 14 15 alert(person1.sayName == person2.sayName); //true
优点:对象的属性和方法都是共享的
缺点:对象的属性需要重新赋值
原型对象的理解:
prototype和原型的关系:prototype(prototype是构造函数的一个属性)是指向原型的指针,原型中的constructor属性又指向原构造函数。
Person.prototype指向原型对象,Person.prototype.constructor指向Person
4、组合使用构造模式和原型模式
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.friends = ["Shelby", "Court"]; 6 } 7 Person.prototype = { 8 constructor: Person, 9 sayName : function () { 10 alert(this.name); 11 } 12 }; 13 14 var person1 = new Person("Nicholas", 29, "Software Engineer"); 15 var person2 = new Person("Greg", 27, "Doctor"); 16 17 person1.friends.push("Van"); 18 19 alert(person1.friends); //"Shelby,Court,Van" 20 alert(person2.friends); //"Shelby,Court" 21 alert(person1.friends === person2.friends); //false 22 alert(person1.sayName === person2.sayName); //true 23
优点:属性在构造函数中定义,constructor和函数在原型中定义
时间: 2024-10-13 05:53:18