我們的志工尚未將本文翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!
您也可以閱讀本文的 English (US) 版本。

Message

TypeError: setting getter-only property "x" (Firefox)
TypeError: Cannot set property "prop" of #<Object> which has only a getter (Chrome)

Error type

TypeError in strict mode only.

What went wrong?

There is an attempt to set a new value to a property for which only a getter is specified. While this will be silently ignored in non-strict mode, it will throw a TypeError in strict mode.

Examples

The example below shows how to set getter for a property. It doesn't specify a setter, so a TypeError will be thrown upon trying to set the temperature property to 30. For more details see also the Object.defineProperty() page.

"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"

To fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this:

"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 }]

See also

文件標籤與貢獻者

 此頁面的貢獻者: fscholz
 最近更新: fscholz,