如果您修改构造函数的原型(prototype)对象,则更改仅对您使用该构造函数创建的新对象可见;使用构造函数创建的现有对象将不受影响。是真是假?
最佳答案
测试起来相当容易:
//
//our constructor
function myThing(){
}
//create a prototype method
myThing.prototype.foo = function(){
return 'bar';
};
//create a prototype property
myThing.prototype.thing = 'hello';
var bar = new myThing();
console.log(bar.foo());//bar
console.log(bar.thing);//hello
//modify prototype
myThing.prototype.foo = function(){
return 'baz';
};
myThing.prototype.thing = 'goodbye';
//create new
var bar2 = new myThing();
//log old
console.log(bar.foo()); //baz
console.log(bar.thing); //goodbye
//log new
console.log(bar2.foo()); //baz
console.log(bar2.thing); //goodbye
//
因此,正如您所看到的,在这种情况下您的声明是错误:如果您的对象正在使用原型(prototype)方法和属性,并且这些方法或属性被修改(同时保持相同的原型(prototype)引用,请参阅Oriol的回答差异),现有对象将受到影响。
关于javascript - 如果修改构造函数的原型(prototype)对象,现有构造函数是否不受影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31947507/