面试常常提问vue双向数据绑定的原理,其主要是依赖于Object.definePropety();vue
Object.definePropety下面有get和set方法。面试
get指读取属性时调用的放法,set是写入属性时调用的方法。this
举个例子:get
var book={it
_year = 2004,io
edition:1function
};原理
Object.defineProperty(book,"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); //2
开始,当book.year=2005时,get获取到this._year的值,而后传值给set,保存新值,this.year=newValue=2005,this.edition=2。同理,将book.year改成2006,那么edition的值应为3,2014应为1.