【问题标题】:why does apply only take one param in this case?为什么在这种情况下 apply 只需要一个参数?
【发布时间】:2011-11-28 19:05:26
【问题描述】:

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

我先定义现状:

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“应用使用给定的 this 值和作为数组提供的参数调用函数。”您可以在案例中看到,使用 apply 我只传递了一个参数,我相信它定义了“this”。你能弄清楚这个方法到底发生了什么吗,为什么应用是必要的,为什么在这种情况下我只能将一个参数传递给该方法,当它声明需要两个时。谢谢。

【问题讨论】:

  • get_status函数不需要参数,所以不需要提供参数。如果提供了它们,无论如何它们都会被忽略。代码可以很容易地使用call
  • .apply 不是必需的,.call 会做同样的事情。 .apply 是将未知数量的参数传递给此处不需要的函数的唯一方法。问题是什么? :)

标签: javascript this var apply


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    并没有说明需要两个:

    fun.apply(thisArg[, argsArray])
    

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

    在您的通话中发生的情况是,您的 statusObject 作为 this 参数传递给您的 get_status 函数。

    这意味着当get_status 执行并执行return this.status 时,它本质上是返回statusObject.status

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

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

    可以在GitHub我的 jQuery 插件框架中找到一个示例

    【讨论】:

      【解决方案3】:

      apply 接受一个参数,即用作this 的对象,后跟参数如果有

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

      【讨论】:

      • 它的 JavaScript,你没有来传递参数。只要你愿意接受不通过的后果:)
      猜你喜欢
      • 2017-07-15
      • 2016-08-08
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多