【发布时间】:2015-04-13 09:59:06
【问题描述】:
为什么我不能为具有冻结原型的非冻结对象分配新属性:
在没有 Object.freeze 的情况下工作:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
以上代码按预期工作,但我想确保默认值不会被意外更改。所以我想冻结我的默认对象:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//!!!!!!!!!!!!
Object.freeze(defaults);
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
//TypeError: Cannot assign to read only property 'sections' of #<Object>
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
我不明白的是,如果它的原型被冻结,为什么我不能分配给 specificObject?
//编辑: 请注意,特定对象未冻结:
'use strict'
//This object will be prototype of next objects
var protoObj = {a: 1, o: {}};
Object.freeze(protoObj);
console.log(Object.isFrozen(protoObj)); //true
var n = Object.create(protoObj);
console.log(Object.isFrozen(n)); //false
【问题讨论】:
-
可能是因为如果原型被冻结,那么它是只读的。你不能对其进行任何更改
-
这就是 Object.freeze 的重点——防止对其进行任何修改。
-
OP 正在尝试修改继承对象,而不是原型。
-
specificObject.__proto__ 指向原型,它是被冻结的默认值
-
您已经使用冻结对象创建了
specificObject。因此,它的原型被冻结,您正在尝试修改冻结的属性。你认为它会如何运作?
标签: javascript prototype ecmascript-5