本文参考:《JavaScript高级程序设计(第三版)》函数
建立自定义类型的最多见方式,就是组合使用构造函数模式与原型模式。ui
构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。this
结果,每一个实例都会有本身的一份实例属性的副本,但同时又共享着对 方法 的引用。spa
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("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.friends.push("Van");
console.log(person1.friends, person2.friends); // [ 'Shelby', 'Court', 'Van' ] [ 'Shelby', 'Court' ]
console.log(person1.friends === person2.friends); // false
console.log(person1.sayName === person2.sayName); // true,都是同一个内存地址,指向 prototype对象。
复制代码
constructor
实例会自动生成 constructor
属性,指向它们的构造函数prototype
console.log(person1.constructor === Person); // true
console.log(person2.constructor === Person); // true
复制代码
instanceof
JS提供 instanceof 运算符,验证原型对象和实例对象的关系设计
console.log(person1 instanceof Person); // true
console.log(person2 instanceof Person); // true
复制代码