标签:
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"); 13 console.log(person1); 14 console.log(person2);
优点:解决了创造对象的问题
缺点:没有解决对象识别的问题 (instanceof -> Object)
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", 30, "Software Engineer"); 10 console.log(person1); 11 person1.sayName(); 12 alert(person1.constructor == Person); 13 alert(person1 instanceof Object); 14 alert(person1 instanceof Person);
优点:解决对象识别的问题 (instanceof -> Object)
缺点:不同实例上的同名函数是不相等的。有this对象在,没有必要在执行代码前把函数绑定到特定的对象上来。
1 function Person(){} 2 Person.prototype.name = "Nicholas"; 3 Person.prototype.age = 29; 4 Person.prototype.job = "software Engineer"; 5 Person.prototype.sayName = function(){ 6 alert(this.name); 7 } 8 9 var person1 = new Person(); 10 person1.sayName(); 11 12 var person2 = new Person(); 13 person2.sayName(); 14 15 alert(person1.sayName == person2.sayName);
优点:不同实例上的同名函数是相等的
缺点:引用对象的值是所有实例共享的,不存在自己独特的属性
1 function Person(name, age, job){ 2 this.name = name; 3 this.age = age; 4 this.job = job; 5 this.friends = ["Shelby","Count"]; 6 } 7 Person.prototype = { 8 constructor : Person, 9 sayName : function(){ 10 alert(this.name); 11 } 12 } 13 var person1 = new Person("Nicholas", 29, "Software Engineer"); 14 var person2 = new Person("Greg", 27, "Doctor"); 15 16 person1.friends.push("Van"); 17 alert(person1.friends); //S,C,V 18 alert(person2.friends); //S,C 19 alert(person1.friends === person2.friends); // false 20 alert(person1.sayName === person2.sayName); //true
优点:同时具有构造函数模式和原型模式的优点
缺点:
function Person(name, age, job){ this.name = name; this.age = age; this.job = job; if(typeof this.sayName != "function"){ Person.prototype.sayName = function(){ alert(this.name); }; } } var friend = new Person ("Nicholas", 29, "Software Engineer"); friend.sayName();
只在sayName() 方法不存在的情况下,才会将它添加的原型中。这段代码只会在初次调用构造函数时才会执行。
function SpecialArray() { var values = new Array(); values.push.apply(values, arguments); values.toPipedString = function(){ return this.join("|"); }; return values; } var colors = new SpecialArray("red", "blue", "green"); alert(colors.toPipedString());
首先,返回的对象与构造函数或者构造函数与原型属性之间没有关系;也就是说,构造函数返回对象与构造函数外部创建的对 象没有什么不同。为此不能依赖instanceof操作符来确定对象类型。建议能用其他模式的情况下,不要使用这种模式。
function Person(name, age, job){ var o = new Object(); //可以在这里自定义私有变量和函数 o.sayName = function(){ alert(name); }; return o; }
标签:
原文地址:http://www.cnblogs.com/juanjuan16/p/5820429.html