console
let obj = {
name: 'jerry',
_name: 'jerry',
age: 18,
_age: 18
};
let app = document.getElementById('app');
app.innerHTML = `我叫${obj.name},今年${obj.age}`
Object.defineProperty(obj, 'age', {
get: function () {
console.log('读取mes:' + this._age);
return this._age;
},
set: function (val) {
this._age = val;
app.innerHTML = `我叫${this.name},今年${this.age}`;
console.log('设置mes:' + val);
}
})
Object.defineProperty(obj, 'name', {
get: function () {
console.log('读取name:' + this._name);
return this._name;
},
set: function (val) {
this._name = val;
app.innerHTML = `我叫${this.name},今年${this.age}`;
console.log('设置name:' + val);
}
})
inputName.oninput = function() {
obj.name = inputName.value
}
inputAge.oninput = function() {
obj.age = inputAge.value
}
<div id="app"></div>
姓名:<input id="inputName" type="text">
<br>
年龄:<input id="inputAge" type="number">