aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/errors/getter_only/index.html
blob: 0636f30eeafe71bdbb4ab8b41735bb28903d444c (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
77
78
79
80
81
82
---
title: 'TypeError: setting getter-only property "x"'
slug: Web/JavaScript/Reference/Errors/Getter_only
tags:
  - JavaScript
  - 严格模式
  - 类型错误
  - 错误提示
translation_of: Web/JavaScript/Reference/Errors/Getter_only
---
<div>{{jsSidebar("Errors")}}</div>

<h2 id="错误提示">错误提示</h2>

<pre class="syntaxbox">TypeError: setting getter-only property "x" (Firefox)
TypeError: Cannot set property "prop" of #&lt;Object&gt; which has only a getter (Chrome)
</pre>

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

<p>仅在<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">严格模式</a>下报 {{jsxref("TypeError")}} 错误。</p>

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

<p>该错误提示出现于试图给一个仅仅设置了 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> 特性的属性赋新值的时候。在非严格模式下会被静默忽略,而在<a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">严格模式</a>下会报 {{jsxref("TypeError")}} 错误。</p>

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

<p>下面的例子展示了如何为一个属性设置 getter 特性。由于没有设置 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a> 特性,所以在试图将 temperature 属性值设置为 30 的时候会报 TypeError 的错误。相关细节信息可以参考 {{jsxref("Object.defineProperty()")}} 页面。</p>

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

function Archiver() {
  var temperature = null;
  Object.defineProperty(this, 'temperature', {
    get: function() {
      console.log('get!');
      return temperature;
    }
  });
}

var arc = new Archiver();
arc.temperature; // 'get!'

arc.temperature = 30;
// TypeError: setting getter-only property "temperature"</pre>

<p>至于修复问题的方法,可以将第 16 行的代码移除,因为它试图为 temperature 属性赋值,或者是为它添加一个 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a> 特性,就像下面这样:</p>

<pre class="brush: js example-good highlight[12]">"use strict";

function Archiver() {
  var temperature = null;
  var archive = [];

  Object.defineProperty(this, 'temperature', {
    get: function() {
      console.log('get!');
      return temperature;
    },
    set: function(value) {
      temperature = value;
      archive.push({ val: temperature });
    }
  });

  this.getArchive = function() { return archive; };
}

var arc = new Archiver();
arc.temperature; // 'get!'
arc.temperature = 11;
arc.temperature = 13;
arc.getArchive(); // [{ val: 11 }, { val: 13 }]</pre>

<h2 id="相关内容">相关内容</h2>

<ul>
 <li>{{jsxref("Object.defineProperty()")}}</li>
 <li>{{jsxref("Object.defineProperties()")}}</li>
</ul>