93   JS

1,通过构造函数的创建的实例,将会获得构造函数的属性,而且这些属性在每个实例中是单独存在的,不会共享的。

来验证下

function Person(name){
this.name = name;
this.sex = ‘boy’;
}
var person1 = new Person(“Nicholas”);
var person2 = new Person(“Greg”);
console.log(person1);
console.log(person2);
person1.sex = ‘girl’;
console.log(person1);
console.log(person2);

 

 

2,有些场景,希望每个实例共享部分属性或者方法,则可以通过修改原型属性来实现

 

function Person(name){
this.name = name;
this.friends = [“Shelby”, “Court”];
}
Person.prototype.sayName =function(){
alert(this.name);
}

Person.prototype.friends =[“Shelby”, “Court”];
var person1 = new Person(“Nicholas”);
var person2 = new Person(“Greg”);
person1.friends.push(“Van”);
alert(person1.friends); //”Shelby,Count,Van”
alert(person2.friends); //”Shelby,Count,Van”
person1.sayName();

person2.sayName();

 

 

3,为了更好地使用以上构造函数和原型模式,可以通过动态修改原型的模式

 

function Person(name){
this.name = name;
this.friends = [“Shelby”, “Court”];

if (typeof this.sayName != “function”){
Person.prototype.sayName = function(){
alert(this.name);
};
}
}

 

 

 




Leave a Reply

Your email address will not be published. Required fields are marked *