Javascript函数:应用Apply

Javascript函数:应用Apply,javascript,Javascript,我被这种奇怪的感觉难住了 假设我有一个数组: var array = [{ something: 'special' }, 'and', 'a', 'bunch', 'of', 'parameters']; 我可以apply函数的apply方法调用函数吗?该对象是{something:'special'},参数是数组的其余部分 换句话说,我可以这样做吗 var tester = function() { console.log('this,', this); console.log

我被这种奇怪的感觉难住了

假设我有一个数组:

var array = [{
  something: 'special'
}, 'and', 'a', 'bunch', 'of', 'parameters'];
我可以
apply
函数的
apply
方法调用函数吗?该
对象是
{something:'special'}
,参数是
数组的其余部分

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

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
但是为什么呢?看来这应该行得通

但是为什么呢

让我们逐步减少通话次数:

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.apply({something: 'special'}, ['and', 'a', 'bunch', 'of', 'parameters']);
哪一个是

tester.call({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters');
因此,对于原始的
数组
,您需要使用

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

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

tester.apply.apply(tester, array);
由于使用了第二种apply方法,第一种方法的调用方式如下:

tester.apply({something: 'special'}, 'and', 'a', 'bunch', 'of', 'parameters');
由于“And”不是数组,因此您会得到您描述的TypeError。您可以使用
调用
方法轻松解决此问题:

tester.call.apply(tester, array);

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

tester.apply(tester,array);是你想要的…@dandavis不是真的。
this
的值应该是
array[0]
,传递的参数应该是
array[1]
array[len-1]
@Ian:对不起,误解了。eval.call.apply(tester,array)可以工作,因为你想应用调用(还不清楚,呵呵)…你可以偷懒:Function.prototype.call===Function.call==truer,实际上,
tester.call
我使用eval,因为它是可靠的,而且只有4个字母没有移位(不像Date和atob)…当然,我只是想强调,函数是在没有特定上下文的情况下访问的——这就是为什么我也把它放在括号中的原因。这肯定是有道理的。只是想得不够透彻。我想……我有点喜欢
apply
ing`apply的绕口令。谢谢