大家都知道原型模式还有构造函数模式,就单独而言他们最大的优点也往往成为他们最大的缺点,下面分享一个JS高程上面的constructor和ptototype结合的例子。
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('Sam', 20 , 'Web-front-end');
var person2 = new Person('Bob', 22, 'policeman')
person1.friends.push('Ashe');
alert(person1.friends); //'Shelby', 'Court', 'Ashe'
alert(person2.friends); //'Shelby', 'Court'
alert(person1.friends === person2.friends); //false
alert(person2.friends === person2.sayName); //true