2017-05-24 45 views
-1

在下面給出的第一個代碼中,對象爲book,開頭的book.year設置爲2013。當我分配book.year = 2015並再次嘗試通過執行book.year來檢索其值時,我仍然得到2013而不是2015。我在哪裏做錯了?Object.defineProperties() - 在定義屬性後爲屬性賦予新值

的代碼如下給出:

var book = {}; 
Object.defineProperties(book, { 
    _yearOrigin: { 
     value: 2013 
    }, 
    edition: { 
     value: "1st" 
    }, 
    year: { 
     get: function(){return this._yearOrigin}, 

     set: function(newValue){ 
      //assigning this._yearOrigin 
      this._yearOrigin = newValue; 

      //carrying the operation for evaluating the `subscript` to add in this.edition 
      //diff = difference in year 
      var diff = String(newValue - 2013); 
      var diffLast2ndChar = diff.charAt(diff.length - 2); 
      var diffLastChar = diff.charAt(diff.length - 1); 
      var subscript = ""; 

      if (diff.length > 1 && diffLast2ndChar == "1") { 
       subscript = "th"; 
      } else { 
       subscript = diffLastChar == "1" 
           ? "st" 
           : diffLastChar == "2" 
            ? "nd" 
            : diffLastChar == "3" 
             ? "rd" 
             : "th" ; 
      } 
      //--end of subscript evaluation 

      //assigment operation of this.edition 
      var rawEdition = Number(this.edition.charAt(0)) + Number(diff); 
      this.edition = String(rawEdition) + subscript; 
     } 
    } 
}); 

>>> book.year = 2015 
>>>book.year //output is 2013 , but expected output is 2015 

然而,在另一方面,在當嘗試檢索的book2.year的值,低於給定的分配book2.year = 2013後另一當量一段代碼,給出預期

輸出 2013
var book2 = { 
    _year: 2004, 
    edition: 1 
}; 
Object.defineProperty(book2, "year", { 
    get: function(){ 
     return this._year; 
    }, 
    set: function(newValue){ 
     if (newValue > 2004) { 
      this._year = newValue; 
      this.edition += newValue - 2004; 
     } 
    } 
}); 

book2.year = 2005; 
console.log(book2.year); //2005 (Now this time the output is expected unlike in the previous code shown above) 
+2

在第一部分要設置你的'_yearOrigin'到'2013'的值作爲常數值。由於您只給出[value](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)參數,因此將其視爲不可變的值。在第二個版本中,您定義了一個對象的屬性,默認值爲「2004」。有一個很大的差異 – Icepickle

+2

由'defineProperties()'與'value'創建的屬性,比如'_yearOrigin',默認爲非['可寫入]](https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)(不可變)。 –

+0

@Ipickle @Jonathan我該怎麼辦?我是否需要指定'writable:true'或其他? – Neel

回答

0

我忽略了一個事實,即「使用Object.Property/Object.properties當定義一個對象的屬性,默認writablefalse,我。 e,定義的值不能改變(不可寫)「這是評論部分中的人提到的。

當我加入writable = true如下圖所示,那麼問題得到有效解決和預期的結果彈出

_yearOrigin: { 
    value: 2013, 
    writable: true 
}, 
+1

不要忘記,現在這也意味着它可以從代碼的任何部分進行設置,而在開放問題中,您使用它更像是私有屬性。這意味着在你的代碼中,你不能再確定_yearOrigin是真正的原點,還是已經設置好了,而沒有在你的單獨設置器中進行檢查 – Icepickle