访问器属性
let obj = {};
Object.defineProperty(obj,'hello',{
get:function(){
console.log("get方法被调用了")
},
set:function(val){
console.log("set方法被调用了,传过来的参数是"+val)
}
})
obj.hello; //get方法被调用了
obj.hello = 'abc'//set方法被调用了,传过来的参数是abc
极简双向绑定的实现
<input type='text' id='test'>
<span id='spa'></span>
<script>
var obj = {};
Object.defineProperty(obj,'hello',{
set:function(newVal){
document.getElementById('test').value = newVal;
document.getElementById('spa').innerHTML= newVal;
}
});
document.addEventListener('keyup',function(e){
obj.hello = e.target.value
})
</script>

结束