繁体   English   中英

javascript:为什么代码不起作用

[英]javascript : why code didn't work

首先,这是我的 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);

在此处输入图片说明

在此处输入图片说明

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

根据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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM