重写原型对象(prototype)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BrightLD/article/details/79066246

重写后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

猜你喜欢

转载自blog.csdn.net/BrightLD/article/details/79066246
今日推荐