03-监听数组变化
<!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>
<script>
let arr = [1, 2, 3]
const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
const methodsToPatch = [
'push',
"pop",
'shift',
'unshift',
'splice',
'sort',
'reverse'
];
methodsToPatch.forEach(function (method) {
const original = arrayProto[method];
Object.defineProperty(arrayMethods, method, {
enumerable: false,
configureable: true,
writable: true,
value: function (...args) {
console.log(`通过${method}方法修改数组`);
const result = original.apply(this, args);
return result;
}
})
});
arr.__proto__ = arrayMethods;
arr.push(1);
console.log(arr);
arr.pop()
console.log(arr);
</script>
</body>
</html>