示例代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Object.defineProperty 及 实现数据双向绑定</title>
<input type="text">
<h1></h1>
</head>
<body>
<script>
const ipt = document.querySelector('input');
const h = document.querySelector('h1');
let hanObj = {
name: '',
_name: ''
};
Object.defineProperty(hanObj, 'name', {
get() {
return hanObj._name;
},
set(sval) {
hanObj._name = sval
h.innerHTML = sval
ipt.value = sval
}
})
ipt.oninput = function () {
hanObj.name = this.value
}
</script>
</body>
</html>
评论 (0)