<span id='spanName'></span><br />
<input type='text' id='inputName'/>
let obj = {
name: ''
}
// 2.0 方式
Object.defineProperty(obj,'name',{
get() {
return this.value;
},
set(val) {
this.value = val;
observer();
}
});
// 3.0 方式
obj = new Proxy(obj, {
get(target, prop) {
return target[prop];
},
set(target, prop, value) {
target[prop] = value;
observer();
}
})
function observer() {
spanName.innerHTML = obj.name;
inputName.value = obj.name;
}
inputName.oninput = function () {
obj.name = this.value;
}
网友评论