JavaScript 函数 : Applying Apply

标签 javascript

我被这种奇怪的事情难住了。

假设我有这个数组:

var array = [{
  something: 'special'
}, 'and', 'a', 'bunch', 'of', 'parameters'];

我可以apply函数的apply方法来调用this对象的函数{something:'special '} 而参数是 array 的其余部分?

换句话说,我可以这样做吗

var tester = function() {
  console.log('this,', this);
  console.log('args,', arguments);
};
tester.apply.apply(tester, array);

期望输出如下?

> this, {"something": "special"}
> args, {"0": "and", "1": "a", "2": "bunch", "3": "of", "4": "parameters"}

我试过了。

TypeError: Function.prototype.apply: Arguments list has wrong type

但是为什么?看起来这应该可行。

最佳答案

But why?

让我们逐步减少调用次数:

tester.apply.apply(tester, array) // resolves to
(Function.prototype.apply).apply(tester, array) // does a
tester.apply({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters');

在这里你可以看到哪里出了问题。正确的是

var array = [
    {something: 'special'},
    ['and', 'a', 'bunch', 'of', 'parameters']
];

然后 apply.apply(tester, array) 会变成

tester.apply({something: 'special'}, ['and', 'a', 'bunch', 'of', 'parameters']);

它做了一个

tester.call({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters');

因此对于您的原始数组,您需要使用

(Function.prototype.call).apply(tester, array)

关于JavaScript 函数 : Applying Apply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686568/

相关文章:

javascript - 为什么这个nodejs代理服务器挂了?

javascript - document.write 多行文本

javascript - ES6 类 : is it possible to access the constructor of a child class from the parent?

javascript - 如何诊断此错误?

javascript - Twitter Bootstrap Datepicker 不会更新输入值

javascript - 缩放后获取 "visible"视口(viewport)区域

javascript - 将 HTML 附加到组件和 React Component 类意外标记,预期 }

javascript - 我应该直接分配 JavaScript 事件来统一代码吗?

javascript - 当谈到 JavaScript 和 CSS 时,你如何命名你的类?

javascript - 如何在v-for循环中通过id获取用户名?