简单原型
除了一个一个地添加原型属性,我们还可以通过对象字面量({}大括号)的形式进行创建
例如:
function CreatPerson () {};
// 第一种,一个一个创建
CreatPerson.prototype.name = 'zhang';
CreatPerson.prototype.age = 12;
// 第二种 对象字面量
CreatPerson.prototype = {
name:'zhang',
age:12
}
var person = new CreatPerson();
person.name||person.age
两种创建,结果是一样的。
不同之处在于:
第一种创建person.constructor指向构造函数
person.constructor == CreatPerson // true
第二种创建person.constructor将不会指向构造函数
person.constructor == CreatPerson // false
原因时创建对象字面量相当于重写了prototype对象,新对象的constructor指向Object构造函数
person.constructor == Object
相同之处:
通过instanceof依然可以得到相同结果
person instanceof CreatPerson // true 两种方法相同
解决方法:
// 第二种 对象字面量
CreatPerson.prototype = {
constructor:CreatPerson,
name:'zhang',
age:12
}
此时的constructor的[[Enumerable]](是否可以枚举,true),默认时false(不可).
可以通过设置Object.defineProperty()进行设置:
Object.defineProperty(CreatPerson.prototype,'constructor',{
enumeralbe:false,
value:CreatPerson
})
原型的动态性
function CreatPerson () {};
var person1 = new CreatPerson();
CreatPerson.prototype = { // 重写对象
constructor:CreatPerson,
name:'zhang',
age:12
}
var person2 = new CreatPerson();
console.log(person1.name) // undefined
console.log(person2.name) // zhang
实例person1实例和原型中没有属性name,此时perosn1的原型是没有重写之前的CreatPerson.prototype
实例person1中的原型是指重写的CreatPerson.prototype对象