这个绑定函数…这些参数,还有这个apply方法.我不确定我理解这在这个例子中是如何工作的

This Bind Function... and these arguments, and this apply method... I'm not sure I understand how this is working in this example

本文关键字:何工作 工作 不确定 参数 函数 绑定 方法 apply      更新时间:2023-09-26

摘自http://ejohn.org/apps/learn/#84

function bind(context, name){ 
  return function(){ 
    return context[name].apply(context, arguments); 
  }; 
} 

我真的想弄明白这是怎么回事。这个函数可以工作,但是,如果您从最内层的函数中获取console.log参数,它们就不存在了。那么,如何在调用它们的apply函数中使用它们呢?

换句话说:

function bind(context, name){ 
  console.log(arguments.length === 2, true);
  return function(){ 
    console.log(arguments.length === 0, true);
    return context[name].apply(context, arguments); 
  }; 
} 

您可以在外部函数中console.log参数并获取长度属性。但是从最里面的函数,参数。

为了简化,暂时不考虑闭包。

函数bind返回如下函数:

function returnedFunction() {
    return context[name].apply(context, arguments);
}

如果我调用returnedFunction(1,2,3);,参数是1, 2, 3。如果我调用returnedFunction(),则没有参数。

现在我们要担心的是contextname,它们在简化后就是undefined,当你看到闭包时,会发现它们是在外部函数中定义的。

argumentsthis不是变量,所以它们不能被关闭。对每个函数调用分别求值。对于传递给bind的任何参数,它们都会为bind求值,然后每次调用returnedFunction时,它们都会为returnedFunction求值。

注意从bind返回的函数彼此之间没有关系。它们都有自己独特的环境,具有不同的contextname绑定。