TypeError: "x" is read-only - JavaScript 编辑

The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.

Message

TypeError: Assignment to read-only properties is not allowed in strict mode (Edge)
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)

Error type

TypeError

What went wrong?

The global variable or object property that was assigned to is a read-only property. (Technically, it is a non-writable data property.)

This error happens only in strict mode code. In non-strict code, the assignment is silently ignored.

Examples

Invalid cases

Read-only properties are not super common, but they can be created using Object.defineProperty() or 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

There are also a few read-only properties built into JavaScript. Maybe you tried to redefine a mathematical constant.

'use strict';
Math.PI = 4;  // TypeError

Sorry, you can't do that.

The global variable undefined is also read-only, so you can't silence the infamous "undefined is not a function" error by doing this:

'use strict';
undefined = function() {};  // TypeError: "undefined" is read-only

Valid cases

'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)

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:124 次

字数:3835

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文