美文网首页
数组操作的方法

数组操作的方法

作者: cherubic_c | 来源:发表于2020-04-23 10:25 被阅读0次
监听数组变化
function monitorArr(arr,callback){
    var arrayProto = Array.prototype;
    var arrayMethods = Object.create(arrayProto);
    var newArrProto = [];
    [
      'push',
      'pop',
      'shift',
      'unshift',
      'splice',
      'sort',
      'reverse'
    ].forEach(function(method){
      // 原生Array的原型方法
      var original = arrayMethods[method];
    
      // 将push,pop等方法重新封装并定义在对象newArrProto的属性上
      // 这里需要注意的是封装好的方法是定义在newArrProto的属性上而不是其原型属性
      // newArrProto.__proto__ 没有改变
      newArrProto[method] = function mutator() {
        console.log('监听到数组的变化啦!');
        original.apply(this, arguments)
        // 调用对应的原生方法并返回结果(新数组长度)
        if (typeof callback == 'function') {
            callback(this);
        }
        //return original.apply(this, arguments);
      }
    })
    arr.__proto__ = newArrProto;
}
function getArr(arr){
    console.log(arr,'123')
}
let arr=[1,2];
//调用
monitorArr(arr,getArr)
arr.push(3)
//结果 getArr console
[1,2,3]

相关文章

网友评论

      本文标题:数组操作的方法

      本文链接:https://www.haomeiwen.com/subject/dbloihtx.html