关于普通对象调用Array.prototype.push方法的一点疑问

各位大神,小弟有一事不明,恳请各路大神不吝赐教,请看代码:

// 类数组
const arrayLike = {
  length: 1,
  0: 'a',
  1: 'b',
  2: 'c',
  3: 'd',
  push: Array.prototype.push
};

为什么按照这样子可以调用Array.prototype.push方法,一般情况下不都是使用Array.prototype.push.call()或者Array.prototype.push.apply()方法进行调用吗?
还有就是为什么按照上述代码arrayLike.push()方法添加元素可以添加到arrayLike对象中去。而我使用arrayLike[Array.prototype.push]调用push方法则会报错。
小弟很是头大,烦请各位大神赐教,小弟在此谢过了

阅读 1.2k
1 个回答

咱一步一步来:

  1. 定义一个对象字面量,这能看懂吧?
let obj = {
   myfunc: function(msg) {
       console.log('hello' + msg);
   }
}

obj.myfunc('hi');
  1. 改成用变量的方式定义函数:
function tmp(msg) {
    console.log('hello' + msg);
}

let obj = {
   myfunc: tmp
}

obj.myfunc('hi');
  1. 现在我们用 Array.prototype.push 替代它:
let obj = {
   myfunc: Array.prototype.push
}

obj.myfunc('hi');
  1. 最后一步,改个名字:
let obj = {
   push: Array.prototype.push
}

obj.push('hi');

最后的区别无非就是一开始那个 myfunc 是你自定义的,而 Array.prototype.push 是内置的、对你来说是黑盒的而已。事实上我们完全也可以实现类似的自定义函数:

let obj = {
   myfunc: function() {
       let current = Math.max(+this.length || 0, 0);
       for (let i = 0; i < arguments.length; i++) {
           this[current] = arguments[i];
           current++;
           this.length = current;
       }
       return current;
   }
}

obj.myfunc('hi1');
obj.myfunc('hi2');
obj.myfunc('hi3', 'hi4', 'hi5');
console.log(obj); // 猜猜看结果是什么?

到此为止,我们就已经实现了一个自定义的 push 方法了。

P.S. 还剩一个知识点,就是 this 指向的问题,但跟本题无关,这属于 JS 基础知识范畴内的了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题