标签:
有如下代码:
function Rabbit() { var jumps = "yes";};var rabbit = new Rabbit();alert(rabbit.jumps); // undefinedalert(Rabbit.prototype.constructor); // outputs exactly the code of the function Rabbit();
改成这样:
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?
那是因为:
Rabbit.prototype.constructor只是一个到原始constructor的引用,用于类实例化的时候检测其构造器。因此,如果你尝试:
Rabbit.prototype.constructor = function Rabbit() { this.jumps = "no";};
你只是打破了原型对象上到原始对象constructor的引用。因此你并不能更改原来的构造器。
为什么无法从prototype修改constructor 函数
标签:
原文地址:http://my.oschina.net/u/214483/blog/476041