javascript:为什么代码不起作用

时间:2017-01-09 16:49:48

标签: javascript

首先,这是我的javascript代码

<script type="text/javascript">
var book = {};

Object.defineProperties(book, {
    _year : {
        value : 2004
    },

    edition : {
        value : 1
    },

    year : {
        get : function () {
            return this._year;
        },

        set : function (newValue) {
            if (newValue > 2004) {
                this._year = newValue;
                this.edition += newValue - 2004;
            }
        }
    }

});

book.year = 2005;
alert(book.edition);
alert(book._year);

enter image description here

enter image description here

谁能帮助我,我很困惑,谢谢

1 个答案:

答案 0 :(得分:4)

根据https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties

,您的基础属性不是writable

以下作品:

var book = {};

Object.defineProperties(book, {
  _year: {
    value: 2004,
    writable: true
  },

  edition: {
    value: 1,
    writable: true
  },

  year: {
    get: function() {
      return this._year;
    },

    set: function(newValue) {
      if (newValue > 2004) {
        this._year = newValue;
        this.edition += newValue - 2004;
      }
    }
  }

});

book.year = 2006;
console.log(book.edition);
console.log(book._year);