更简单的原型语法
function Person2() {}
console.log(Person2.prototype.constructor); 指向Person2
如果我们用对象字面量重写原型对象会出现什么情况?
Person2.prototype = {
name: 'tianxia',
age: 18,
sayName: function() {
console.log(this.name);
}
}
我们发现
console.log(Person2.prototype.constructor); //指向的是Object
1.为什么指向Object呢?
2.instanceof操作符用于测试构造函数的prototype属性是否出现在对象原型链中的任何位置?
3.为什么要设置value值?
Object.defineProperty(Person2.prototype,'constructor',{
enumerable: false,
value: Person2,
});
function Person3() {}
var friend = new Person3();
Person3.prototype = {
name: 'xiao0411',
age: 22,
sayName: function() {
console.log(this.name);
}
}
console.log(friend.__proto__);
friend.sayName(); //TypeError: friend.sayName is not a function
上面写会报错,下面这样写为何没有问题呢?
function Person3() {}
Person3.prototype = {
name: 'xiao0411',
age: 22,
sayName: function() {
console.log(this.name);
}
}
var friend = new Person3();
console.log(friend.__proto__);
friend.sayName(); //TypeError: friend.sayName is not a function