调用函数原型方法改this

169 阅读1分钟

通过对象属性模拟一个空数组,通过数组的prototype原型方法利用函数的call()传参,改第一个参数里面的this,即当前的this指向该模拟数组,然后就可以往空数组里push数组元素了,遍历打印出新数组,js代码如下:

 var arr1 = {
            length: 0,
            push(val) {
                Array.prototype.push.call(this, val)
            },
            forEach(fn) {
                Array.prototype.forEach.call(this, fn)
            }
        }
        arr1.push('aaa')
        arr1.push('bbb')

        arr1.forEach(r => {
            console.log(r);

        });