2013-10-13 45 views
12

我試圖創建getter和setter方法的對象,這是我的代碼:Google Chrome Object.defineProperty中的錯誤行爲?

var Player = function(height){ 
    var _height = height; 

    Object.defineProperty(this, 'height', { 
     enumerable: false 
    , configurable: true 
    , writable: false 
    , get: function(){return _height;} 
    , set: function(val){_height = val;} 
    }); 
} 

VAR myPlayer =新播放器(10);

即使的defineProperty選項writable屬性設置爲false,我得到以下錯誤:

Invalid property. A property cannot both have accessors and be writable or have a value, #<Object>

writable設爲當然是真的一樣正在發生,但錯誤如果我刪除writable行消失。

我做錯了什麼,或者這是一個錯誤?這是發生在谷歌瀏覽器,版本30.0.1599.66

+1

錯誤似乎是描述性的......爲什麼你會得到一個不可寫屬性的getter和setter? – elclanrs

+1

錯誤在兩種情況下都得到顯示,'writable:true'和'writable:false'。這不奇怪嗎? – Loupax

+1

您只能擁有'writable'和'value'或'get'和'set'屬性,而不是它們的混合。既然你指定了'writable',你就不能使用'get'或'set'。請參閱[Mozilla MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) –

回答

32

Mozilla MDNObject.defineProperty闡明瞭這一點:

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

這意味着,你可以使用其中的一個:

  • writablevalue
  • get and set

但是你不能使用它們的任何組合。在你的例子中,你指定writable屬性,這意味着它是一個數據描述符,它不允許getset屬性。

相關問題