相关疑难解决方法(0)

为什么不能从原型改变构造函数?

我有这样的例子.

function Rabbit() {
    var jumps = "yes";
};
var rabbit = new Rabbit();
alert(rabbit.jumps);                    // undefined
alert(Rabbit.prototype.constructor);    // outputs exactly the code of the function Rabbit();
Run Code Online (Sandbox Code Playgroud)

我想更改代码,Rabbit()以便var jumps公开.我是这样做的:

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 constructor
alert(rabbit2.jumps);                   // but still outputs undefined
Run Code Online (Sandbox Code Playgroud)

为什么不能以这种方式更改构造函数中的代码?

javascript oop prototype

51
推荐指数
1
解决办法
3万
查看次数

标签 统计

javascript ×1

oop ×1

prototype ×1