Object.defineProperty 和new Proxy深度检测
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <input type="text" inputmode="email" accesskey="b" tabindex="1"> -->
<h3 id="firstname"></h3>
<h3 id="lastname"></h3>
<h3 id="age"></h3>
<script>
let user = {
name: '大海一',
age: 12,
user1: {
addr: '3333'
}
}
function _isObject(obj) {
return typeof obj === 'object' && obj !== null
}
function observeObjProperty(obj) {
for (let key in obj) {
let initVal = obj[key]
if (_isObject(obj[key])) {
observeObjProperty(obj[key])
}
Object.defineProperty(obj, key, {
get() {
console.log('get')
return initVal
},
set(val) {
console.log('set')
if (initVal !== val) {
initVal = val
}
}
})
}
}
function observeObj(obj) {
let proxy = new Proxy(obj, {
get(target, pro) {
console.log('get')
let newObj = target[pro]
if (_isObject(newObj)) {
newObj = observeObj(newObj)
}
return newObj
},
set(target, pro, val) {
console.log('set')
if (target[pro] !== val) {
target[pro] = val
}
}
})
return proxy
}
//observeObjProperty(user)
let userproxy = observeObj(user)
</script>
</body>
</html>