爲何沒法從prototype修改constructor 函數

有以下代碼:
this

function Rabbit() {
    var jumps = "yes";};var rabbit = new Rabbit();alert(rabbit.jumps);                    // undefinedalert(Rabbit.prototype.constructor);    // outputs exactly the code of the function Rabbit();

改爲這樣:prototype

Rabbit.prototype.constructor = function Rabbit() {
    this.jumps = "no";};alert(Rabbit.prototype.constructor);    // again outputs the code of function Rabbit() and with new this.jumps = "no";var rabbit2 = new Rabbit();             // create new object with new constructoralert(rabbit2.jumps);                   // but still outputs undefined

爲何jumps仍是undefined?code

那是由於:對象

 Rabbit.prototype.constructor只是一個到原始constructor的引用,用於類實例化的時候檢測其構造器。所以,若是你嘗試:原型

Rabbit.prototype.constructor = function Rabbit() {
    this.jumps = "no";};

你只是打破了原型對象上到原始對象constructor的引用。所以你並不能更改原來的構造器。it

相關文章
相關標籤/搜索