如果修改构造函数的原型对象,现有构造函数是否不受影响?
Does existing constructor remain unaffected if you modify the prototype object for a constructor function?
如果您修改构造函数的原型对象,则更改仅对您使用该构造函数创建的新对象可见;使用构造函数创建的现有对象将不受影响。对还是错?
没错。魔术是通过内部 [[Prototype]] 属性 完成的,它确定该对象从哪个其他对象继承。
当你实例化一个构造函数时,实例的 [[Prototype]] 被设置为当前的 prototype
。
稍后更改 prototype
不会影响之前的实例,它们的 [[Prototype]] 仍将指向之前的 prototype
。
更改只会影响更改后创建的实例,它们的 [[Prototype]] 将设置为新的 prototype
。
function F(){}
var f1 = new F();
f1 instanceof F; // true
F.prototype = {foo: 'bar'}
var f2 = new F();
f1.foo; // undefined
f2.foo; // "bar
f1 instanceof F; // false
f2 instanceof F; // true
测试起来相当容易:
//
//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
//
所以你可以看到你的陈述在这种情况下是 false:如果你的对象正在使用原型方法和属性并且这些方法或属性被修改(同时保持相同原型参考,请参阅 Oriol 的回答以了解差异),现有对象将受到影响。
我不太清楚你的意思。现有实例不受影响是
- true当你将构造函数的
.prototype
属性设置为不同的原型对象时
- false 当您通过设置属性修改原型对象时。
如果您修改构造函数的原型对象,则更改仅对您使用该构造函数创建的新对象可见;使用构造函数创建的现有对象将不受影响。对还是错?
没错。魔术是通过内部 [[Prototype]] 属性 完成的,它确定该对象从哪个其他对象继承。
当你实例化一个构造函数时,实例的 [[Prototype]] 被设置为当前的 prototype
。
稍后更改 prototype
不会影响之前的实例,它们的 [[Prototype]] 仍将指向之前的 prototype
。
更改只会影响更改后创建的实例,它们的 [[Prototype]] 将设置为新的 prototype
。
function F(){}
var f1 = new F();
f1 instanceof F; // true
F.prototype = {foo: 'bar'}
var f2 = new F();
f1.foo; // undefined
f2.foo; // "bar
f1 instanceof F; // false
f2 instanceof F; // true
测试起来相当容易:
//
//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
//
所以你可以看到你的陈述在这种情况下是 false:如果你的对象正在使用原型方法和属性并且这些方法或属性被修改(同时保持相同原型参考,请参阅 Oriol 的回答以了解差异),现有对象将受到影响。
我不太清楚你的意思。现有实例不受影响是
- true当你将构造函数的
.prototype
属性设置为不同的原型对象时 - false 当您通过设置属性修改原型对象时。