aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/不能添加属性/index.html
blob: cceeb330c4e97d9851c81d68fd49ad75bf0a0701 (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
---
title: 'TypeError: can''t assign to property "x" on "y": not an object'
slug: Web/JavaScript/Reference/Errors/不能添加属性
translation_of: Web/JavaScript/Reference/Errors/Cant_assign_to_property
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="信息">信息</h2>

<pre class="syntaxbox">TypeError: <code class="highlighted" id="line-87">can't assign to property "x" on {y}: not an object</code> (Firefox)
TypeError: Cannot create property 'x' on {y} (Chrome)
</pre>

<h2 id="错误类型">错误类型</h2>

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

<h2 id="原因">原因</h2>

<p>{{jsxref("Strict_mode")}}下, 当试图给一个{{Glossary("symbol")}},{{Glossary("string")}},{{Glossary("number")}}或者一个{{Glossary("boolean")}}类型的数据创建一个属性时就会报 {{jsxref("TypeError")}}, 任何 {{Glossary("Primitive")}} 值都不允许有{{Glossary("property/JavaScript", "property")}}.</p>

<p>这个问题可能是由一个错误的值被放在了一个错误的地方导致的, 或者预期{{jsxref("String")}}{{jsxref("Number")}}的对象变体</p>

<p> </p>

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

<h3 id="错误的情况">错误的情况</h3>

<pre class="brush: js example-bad">'use strict';

var foo = "my string";
// 下面这行代码在非严格模式下不会执行.
foo.bar = {}; // <span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body">TypeError: can't assign to property "bar" on "my string": not an object</span></span></span>
</pre>

<h3 id="如何正确使用">如何正确使用</h3>

<p>有两种方式, 第一种修复这部分代码阻止{{Glossary("primitive")}}被用于这种情况, 或者可以通过使用对象构造器创建来修复.</p>

<pre class="brush: js example-good">'use strict';

var foo = new String("my string");
foo.bar = {};
</pre>

<h2 id="页面相关">页面相关</h2>

<ul>
 <li>{{jsxref("Strict_mode")}}</li>
 <li>{{Glossary("primitive")}}</li>
</ul>