// const data = {
// name: '',
// text: '123'
// };
// function say(name) {
// const arr = {
// '古天乐': '给大家推荐一款超好玩的游戏',
// '渣渣辉': '戏我演过很多,可游戏我只玩贪玩懒月',
// }
// console.log(arr[name]||'来做我的兄弟');
// }
// // 遍历对象,对其属性值进行劫持
// Object.keys(data).forEach(function(key) {
// Object.defineProperty(data, key, {
// enumerable: true,
// configurable: true,
// get: function() {
// console.log('get');
// },
// set: function(newVal) {
// // 当属性值发生变化时我们可以进行额外操作
// console.log(`大家好,我系${newVal}`);
// say(newVal);
// },
// });
// });
// data.name = '45';
const data = {
text: '123'
};
Object.keys(data).forEach((key) => {
Object.defineProperty(data, key, {
get: function () {
console.log('get val');
},
set: function (newVal) {
console.log('set val:' + newVal);
document.getElementById('input').value = newVal;
document.getElementById('p').innerHTML = newVal;
}
});
})
const input = document.getElementById('input');
input.addEventListener('keyup', function (e) {
data.text = e.target.value;
})
<main>
<p>请输入:</p>
<input type="text" id="input">
<p id="p"></p>
</main>