此示例创建一个对象,将其卡住,然后从卡住的对象创建一个新对象。 如果第二个对象试图更改测试属性,则它不能。它仍然卡住 第一个对象的值为 10。
//Create an object and freeze it
var first = {
test: 10
};
Object.freeze(first);
//Create a second object from the first one and
//try and change the new test property (you can't)
var second = Object.create(first);
second.test = 20;
console.log(second.test); //10
这是我的问题:
second.test
是新对象的新属性,还是只是对卡住的第一个对象中属性的引用?
是否可以使用卡住的 first.test
作为默认值,但在需要时让 second.test
覆盖它?
我问的原因是因为我想制作一个不可变的基础对象作为具有默认值的模板,然后用它来制作我可以自定义的新对象。最好的方法是什么?
谢谢!
最佳答案
second
实际上是一个新对象,first
是second
的原型(prototype)。原因
second.test = 20;
不起作用是因为在赋值时,它会查找原型(prototype)上的设置(即 configurable
、enumerable
、writable
、[[Extensible]]
),如果其中任何一个为 false1,则不分配给实例。要直接分配给实例,您必须在 second
上使用 Object.defineProperty
:
var first = {
test: 10
};
Object.freeze(first);
var second = Object.create(first);
Object.defineProperty(second, 'test', { value: 20, enumerable: true, configurable: true, writable: true });
console.log(second.test); // 20
关于javascript - 从卡住的父对象创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19698533/