Errors: Read-only
Errors: Read-only
信息
TypeError: "x" is read-only (Firefox)
TypeError: 0 is read-only (Firefox)
TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome)
TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)
错误类型
TypeError
哪里出错了?
全局变量或对象属性被设置为只读 (专业点讲,就是这条数据属性禁止写入.)
这条错误值发生在strict mode code(俗称严格模式). 正常情况下,是没有报错的
示例
无效的情况
只读属性不能直接创建, 但我们可以通过Object.defineProperty()
或Object.freeze()
设置.
'use strict';
var obj = Object.freeze{name: 'Elsa', score: 157}
obj.score = 0; // TypeError
'use strict';
Object.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false}
LUNG_COUNT = 3; // TypeError
'use strict';
var frozenArray = Object.freeze([0, 1, 2]
frozenArray[0]++; // TypeError
JavaScript中还内置了一些只读属性。尝试重新定义一个数学常数。
'use strict';
Math.PI = 4; // TypeError
报错了
全局变量undefined
也是只读的, 所以你不能忽视臭名昭著的"undefined
is not a function"错误:
'use strict';
undefined = function() {}; // TypeError: "undefined" is read-only
下面这样都是有效,不报错的
'use strict';
var obj = Object.freeze{name: 'Score', points: 157}
obj = {name: obj.name, points: 0}; // replacing it with a new object works
'use strict';
var LUNG_COUNT = 2; // a `var` works, because it's not read-only
LUNG_COUNT = 3; // ok (anatomically unlikely, though)