重寫原型對象(prototype)

重寫後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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章