Javascript功能:应用Apply

时间:2013-07-16 20:41:28

标签: 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

但为什么呢?看起来这应该有效。

2 个答案:

答案 0 :(得分:11)

  

但为什么?

让我们一步一步减少你的电话:

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');

因此,使用原始array,您需要使用

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

答案 1 :(得分:0)

apply方法对this上下文使用一个参数,为要应用的参数使用一个参数。第二个参数必须是数组。

tester.apply.apply(tester, array);

由于第二个apply方法,第一个将被调用如下:

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

由于'和'不是数组,因此您将获得所描述的TypeError。您可以使用call方法轻松解决此问题:

tester.call.apply(tester, array);

call将采用单个参数而不是数组,这将产生所需的结果。

相关问题