从冻结的父对象创建新对象 [英] Creating new objects from frozen parent objects
问题描述
此示例创建一个对象,冻结它,然后从冻结对象创建一个新对象。
如果第二个对象试图更改测试属性,则不能。它仍然被
第一个对象的值10冻结。
This example creates an object, freezes it, and then creates a new object from the frozen object. If the second object tries to change the test property, it can't. It remains frozen with the first object's value of 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
覆盖它to?
Is second.test
a new property on a new object, or is it just a reference to the property in the frozen first object?
Is it possible to use the frozen first.test
as a default value, but let second.test
overwrite it if it needs to?
我问的原因是因为我想把一个不可变的基础对象作为一个带有默认值的模板,然后用它来制作我能做的新对象定制。什么是最好的方法?
My reason for asking is because I want to make an immutable a base object as a template with default values, and then use it to make new objects that I can customize. What's the best approach for this?
谢谢!
推荐答案
second
实际上是一个新对象,第一个
是第二个$ c的原型$ C>。之所以
second
is in fact a new object, with first
being the prototype of second
. The reason why
second.test = 20;
不起作用是因为在分配时,它将寻找原型上的设置(即可配置
,可枚举
,可写
, [ [Extensible]]
)如果其中任何一个为false 1 ,则不分配给实例。要直接分配给实例,您必须在 second
上使用 Object.defineProperty
:
does not work is because upon assignment, it will look for the settings on the prototype (i.e. configurable
, enumerable
, writable
, [[Extensible]]
) and not assign to the instance if any of these are false1. To assign directly to the instance, you'll have to use Object.defineProperty
on second
:
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
1: [[Put]]
:ECMAScript规范, §8.12.5
1: [[Put]]
: the ECMAScript Specification, §8.12.5
这篇关于从冻结的父对象创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!