为什么在这种情况下只适用一个参数?

时间:2011-11-28 19:05:27

标签: javascript this var apply

我正在学习apply,我正在努力理解为什么我正在研究的代码只传递一个参数来应用。

我首先定义Quo:

var Quo = function(string) {
  this.status = string;
};

接下来我定义了get_status:

Quo.prototype.get_status = function() {
  return this.status;
};

我定义了statusObject:

var statusObject = {
  status: 'yo!'
};

这就是我迷失的地方:

var status = Quo.prototype.get_status.apply(statusObject);
// status is 'yo!'

根据documentation“应用调用具有给定值的函数和作为数组提供的参数。”你可以在这种情况下看到,使用apply我只传递一个参数,我相信这个参数定义了“this”。你能清楚一下这个方法究竟发生了什么,为什么需要应用,为什么在这种情况下我只能将一个参数传递给方法,当它需要两个时。谢谢。

3 个答案:

答案 0 :(得分:3)

apply设置应用于第一个参数中提供的对象的函数的上下文。

var o;
function baz(a, b, c) {
  //do stuff
}

o = {
  foo: 'bar'
};

baz.apply(o);
//this is o
//a is undefined
//b is undefined
//c is undefined

如果将数组作为第二个参数传递,则将根据数组中的值设置参数:

baz.apply(o, [1,2,3]);

//this is o
//a is 1
//b is 2
//c is 3

apply中的第二个参数是可选的,但call通常用于设置上下文:

//these do the same thing
baz.call(o);
baz.apply(o);

//this is how they're different
baz.call(o, 1, 2, 3);
baz.apply(o, [1, 2, 3]);

答案 1 :(得分:2)

并未说明需要两个:

fun.apply(thisArg[, argsArray])

注意括号中的argsArray如何,它是可选的。

您的通话中发生的事情是statusObject作为this参数传递给您的get_status功能。

这意味着当get_status执行return this.statusstatusObject.status时,它本质上会返回methods = { init: function(message) { alert(message); } }; function executeFunc(method) { methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } //now I can call like this: executeFunc('init', 'Hey there, this is a message');

Apply非常有用,其中一个原因是动态调用方法。我可以像这样传递要调用的对象中的方法的字符串名称:

{{1}}

可以在GitHub

上的jQuery插件框架中找到此示例

答案 2 :(得分:0)

apply接受一个参数,该对象用作this,后跟参数(如果有的话)

如果函数不带参数,例如你有function f() { ... },你不需要传递任何参数,所以你可以拨打f.apply(someObject);

相关问题