重写原型对象(prototype)

重写后constructor属性的变化以及处理javascript


//建立一个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属性的可枚举性php

Object.keys(Parent.prototype);
//["constructor", "age", "name", "sayAge", "sex"]

Object.definePrototype()方法来对枚举性进行处理java

Object.defineProperty(Parent.prototype,"constructor",{
    enumerable:false,
    value:Parent
});

再次检测web

Object.keys(Parent.prototype);
//["age", "name", "sayAge", "sex"]

原型的调用问题svg

重写原型对象切断了现有原型和任何以前已经存在实例之间的关系;他们应用的还是最初的原型。this

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