Object.freeze()
Values cannot be changed for data properties. Accessor properties (getters and setters) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen whereafter its elements cannot be altered. No elements can be added or removed from it as well.
'use strict'
document.body.innerHTML = "Hello#1";
var frozen = Object.freeze(document.body);
document.body = frozen;
console.log("Same frozen body (First):", document.body === frozen)
console.log(document.body['innerHTML']);
// Why I can modify this property?
document.body.innerHTML = "Hello#2";
console.log("Same frozen body (Second):", document.body === frozen);
console.log(document.body['innerHTML']);
此代码片段使用 getter
和 setter
(此方法失败)
'use strict'
var myObj = {
a: "Ele#1",
get innerHTML() {
return this.a;
},
set innerHTML(html) {
this.a = html;
}
}
myObj = Object.freeze(myObj);
myObj.innerHTML = "Ele";
console.log(myObj);
为什么“卡住”body对象后,我可以修改它的属性?例如,innerHTML
?
可能我缺乏信息,我不知道!
最佳答案
innerHTML
是一个访问器属性。如果您将 document.body
调试到控制台并深入原型(prototype)链,您可以看到它在 Element
中定义为 get innerHTML()
和设置innerHTML()
。
这是一个简单的示例,说明如何实现相同的目标:
var myObj = (function() {
var html = null;
return {
get innerHTML() { return html; },
set innerHTML(value) { html = value; }
};
})();
关于javascript - 为什么在 "freezing"之后的document.body对象,我可以修改它的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49679549/