aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/javascript/reference/errors/cant_assign_to_property/index.html
blob: d1316fe4f932b9dedc48087063abaf1edbcb7aee (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/Cant_assign_to_property
translation_of: Web/JavaScript/Reference/Errors/Cant_assign_to_property
---
<div>{{jsSidebar("Errors")}}</div>

<div>Ошибка строгого режима JavaScript "can't assign to property" ("невозможно присвоить свойство") происходит в тот момент, когда вы пытаетесь создать свойство примитивного типа данных (такого как символ, строка, число или булевое значение). Примитивные типы данных не могут содержать никаких свойств. </div>

<h2 id="Message">Message</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="Error_type">Error type</h2>

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

<h2 id="What_went_wrong">What went wrong?</h2>

<p>In {{jsxref("Strict_mode")}}, a {{jsxref("TypeError")}} is raised when attempting to create a property on <a href="/en-US/docs/Glossary/primitive">primitive</a> value such as a <a href="/en-US/docs/Glossary/symbol">symbol</a>, a <a href="/en-US/docs/Glossary/string">string</a>, a <a href="/en-US/docs/Glossary/number">number</a> or a <a href="/en-US/docs/Glossary/boolean">boolean</a>. <a href="/en-US/docs/Glossary/Primitive">Primitive</a> values cannot hold any <a href="/en-US/docs/Glossary/property/JavaScript">property</a>.</p>

<p>The problem might be that an unexpected value is flowing at an unexpected place, or that an object variant of a {{jsxref("String")}} or a {{jsxref("Number")}} is expected.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Invalid_cases">Invalid cases</h3>

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

var foo = "my string";
// The following line does nothing if not in strict mode.
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="Fixing_the_issue">Fixing the issue</h3>

<p>Either fix the code to prevent the <a href="/en-US/docs/Glossary/primitive">primitive</a> from being used in such places, or fix the issue is to create the object equivalent {{jsxref("Object")}}.</p>

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

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

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Strict_mode")}}</li>
 <li><a href="/en-US/docs/Glossary/primitive">primitive</a></li>
</ul>