hook array push

发布时间 2023-10-22 17:55:03作者: AngDH

 

 

 

let arr = [1, 2, 3];

let proxy = new Proxy(arr, {
  get(target, prop) {
    if (prop === 'push') {
      return function(...args) {
        console.log('push方法被调用了');
        return target[prop].apply(target, args);
      }
    } else {
      return target[prop];
    }
  }
});

proxy.push(4); // 输出:push方法被调用了
console.log(proxy); // 输出:[1, 2, 3, 4]

 

 

 

const arr = [1, 2, 3];

const originalPush = Array.prototype.push;

Array.prototype.push = function(...args) {
  console.log('push 方法被调用了');
  // 执行我们自己的逻辑
  // ...

  // 调用原本的 push 方法
  return originalPush.apply(this, args);
}

arr.push(4); // 控制台输出 "push 方法被调用了"