aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/read-only/index.html
blob: ecdc225497caed898d88e3080c21758299b90c84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
---
title: 'TypeError: "x" is read-only'
slug: Web/JavaScript/Reference/Errors/Read-only
translation_of: Web/JavaScript/Reference/Errors/Read-only
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="报错消息">报错消息</h2>

<pre class="syntaxbox">TypeError: "x" is read-only (Firefox) //格式错误:"x"只读。(x可以代表任意值)
TypeError: 0 is read-only (Firefox)
TypeError: Cannot assign to read only property 'x' of #&lt;Object&gt; (Chrome)
//格式错误:对象的x属性是只读的不能设置 (chrome)
TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)
</pre>

<h2 id="错误格式">错误格式</h2>

<p>{{jsxref("TypeError")}}</p>

<h2 id="哪里出错了">哪里出错了?</h2>

<p>全局变量或对象属性被设置为只读 (专业点讲,就是这条数据属性禁止写入.)</p>

<p>这条错误值发生在<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode code</a>(俗称严格模式). 正常情况下,是没有报错的。</p>

<h2 id="例如">例如</h2>

<h3 id="无效例子(也就是下面这么做会导致报这种错)">无效例子(也就是下面这么做会导致报这种错)</h3>

<p>只读属性不能直接创建, 但我们可以通过{{jsxref("Object.defineProperty()")}}{{jsxref("Object.freeze()")}}设置.</p>

<pre class="brush: js example-bad">"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</pre>

<p>傻了吧,报错了</p>

<p><code>全局变量undefined也是只读的</code>, 所以你不能忽视臭名昭著的"undefined is not a function"错误:</p>

<pre class="brush: js example-bad">"use strict";
undefined = function () {};  // TypeError: "undefined" is read-only
</pre>

<h3 id="下面这样都是有效,不报错的">下面这样都是有效,不报错的</h3>

<pre class="brush: js example-good">"use strict";
var obj = Object.freeze({name: "Score", points: 157});
obj = {name: obj.name, points: 0};   // 用一个新对象替换原来的对象(其实就是更改了对象的指针)

"use strict";
var LUNG_COUNT = 2;  //
LUNG_COUNT = 3;  //
</pre>

<h2 id="参见">参见</h2>

<ul>
 <li>{{jsxref("Object.defineProperty()")}}</li>
 <li>{{jsxref("Object.freeze()")}}</li>
 <li><a href="https://www.answers.com/Q/Which_animals_have_three_lungs">"Which animals have three lungs?" on answers.com</a></li>
 <li><a href="https://aliens.wikia.com/wiki/Klingon">Klingons</a> (another answer to that query)</li>
</ul>