重写后constructor属性的变化以及处理
//创建一个Parent实例
function Parent() {
this.name = "wgh";
}
//重写Parent的原型对象,并为其手动添加constructor属性,注意在ECMAScript5中默认的constructor是不可枚举的,但是我们手动设置的是可以枚举的,如果要处理的话我们可以通过Object.definePrototype()方法来设置
Parent.prototype={
constructor:Parent,
age:23,
name:"王光辉",
sayAge:function () {
console.log(this.age);
},
sex:"男"
};
let p1 = new Parent();
检测重写的原型对象constructor属性的可枚举性
Object.keys(Parent.prototype);
//["constructor", "age", "name", "sayAge", "sex"]
Object.definePrototype()方法来对枚举性进行处理
Object.defineProperty(Parent.prototype,"constructor",{
enumerable:false,
value:Parent
});
再次检测
Object.keys(Parent.prototype);
//["age", "name", "sayAge", "sex"]
原型的调用问题
重写原型对象切断了现有原型和任何之前已经存在实例之间的关系;他们应用的仍是最初的原型。
function Parent() {
this.name = "wgh";
}
//注意我们在这里创建了一个实例p2
var p2=new Parent();
//重写原型对象
Parent.prototype={
constructor:Parent,
age:23,
name:"王光辉",
sayAge:function () {
console.log(this.age);
},
sex:"男"
};
p2.sayAge();//p2.sayAge is not a function
本文探讨了在JavaScript中重写构造函数后的prototype属性变化,特别是constructor属性的可枚举性调整及其对实例方法的影响。通过具体示例展示了如何使用`Object.defineProperty()`方法来修改属性的可枚举特性。
478

被折叠的 条评论
为什么被折叠?



