关于JavaScript中对象读取属性的问题

 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;
                }
            }
        }
    });

代码如上,为啥在get属性的方法里面返回的是一个undefined呢?

图片说明

应该是this的问题,js对象使用this之前,在对象开始前先替换一下 _this=this

可能是this的问题,js对象使用this之前,在对象开始前先替换一下 _this=this

this指向是的 year,作用域没到 year之外

试试把year去掉,get、set和_year同级试试?
这种处理一般都在后台进行,前台很少写这么复杂的

 _year: {
            value: 2004      
        },
        edition: {
            value: 1
        },
        get: function(){
            return this._year.value;
        },
        set: function(newValue){
            if(newValue > 2004){
                this._year.value = newValue;
                this.edition.value += newValue - 2004;
            }
        }

你的代码测试可以执行,只不过edition不可写,稍微修改一下。

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

},
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 = 2005;
alert(book.edition);

//firefox firebug test

这玩意儿不能修改吗?重新发一下,没加代码块。

你的代码测试可以执行,只不过edition不可写,稍微修改一下。

var book = {};
Object.defineProperties(book,{
    _year:{
        value:2004
    },
    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 = 2005;
alert(book.edition);

//firefox firebug test

不会返回undefined,不过你的_year,edition没有添加writable属性,默认false,无法通过year给_year,edition设置值。
https://msdn.microsoft.com/library/ff800817%28v=vs.94%29.aspx
https://msdn.microsoft.com/zh-cn/library/hh965578%28v=vs.94%29.aspx