我对只读属性的含义有点困惑?我知道这classList
是 MDN 定义的只读属性,但这到底是什么意思?
问问题
436 次
3 回答
6
只读属性意味着它不能被覆盖或分配给它。在非严格模式下,任何此类分配都不会默默地执行任何操作。例如:
var obj = {};
Object.defineProperty(obj, 'property', {value: 123, writeable: false})
// Assign 456 to obj.property using the . syntax, but it's still 123
obj.property = 456;
console.log(obj.property);
// Assign 789 to obj.property using the [] syntax, but it's still 123
obj['property'] = 789;
console.log(obj['property']);
或者只是TypeError
在严格的中间出错:
'use strict';
var obj = {};
Object.defineProperty(obj, 'property', {value: 123, writeable: false})
// Assign 456 to obj.property in strict mode will result in a TypeError
obj.property = 456;
console.log(obj.property);
于 2021-01-01T21:41:07.993 回答
2
当属性是只读的时,该属性被称为“不可写”。它不能被重新分配。
classList
例如,您不能更新或为元素的属性赋值,但您可以读取它。
以供参考:
于 2021-01-01T21:52:08.027 回答
1
除了@Mureinik所说的之外,还有另一种方法可以在只读模式下创建一个对象,它调用freeze
你可以像这个例子一样使用它
let myObj = {id: 45, title: 'title here'}
Object.freeze(myObj);
myObj.title = 'update title' // this wouldn't updates
console.log(myObj)
// incase if you want to rewrite this object after freezing it
// you need to re-assign all of its values like this
myObj = {id: myObj.id, title: 'Another title here'}
console.log(myObj)
您可以阅读有关Object.freeze()以及在mdn docs中更新它的正确方法
于 2021-01-01T21:53:19.010 回答