JavaScript 使用记录

JavaScript 理解对象 2 定义多个属性

2017-12-11  本文已影响32人  赵者也
定义多个属性

我们可以使用 Object.defineProperties 方法一次定义多个属性:

        var book = {};
        Object.defineProperties(book, {
                                    __year: {
                                        value: 2014,
                                        writable: true
                                    },
                                    edition: {
                                        value: 1,
                                        writable: true
                                    },
                                    year: {
                                        get: function() {
                                            return this.__year;
                                        },
                                        set: function(newValue) {
                                            if (newValue > 2014) {
                                                this.__year = newValue;
                                                this.edition += newValue - 2014;
                                            }
                                            console.log(this.__year);
                                        }
                                    }
                                });

        book.year = 2017;
        console.log(book.edition);

输出结果:

输出结果
上一篇下一篇

猜你喜欢

热点阅读