有什么方法可以使用 .bind 或 .apply 为被调用方法提供调用方法或循环的范围?

Is there some way to use .bind or .apply to give a called method the scope of the calling method or loop?

function foo(itemA) {
  async.waterfall(
    [
      function(callback) {
        console.log("I can see itemA as " + itemA); // <-- this works fine
        callback(null);
      },
      outerFunction // <-- this method doesn't have access to itemA
    ],
    function(err, item) {}
  );
}

function outerFunction(callback) {
  //item A is not defined so this barfs
  console.log("I'm going to throw an exception cause... " + itemA);
}

为了简洁起见,我既不想在瀑布中定义我的所有函数,也不想玩各种精心设计的游戏,传递一些包含值的对象,以便这些方法可以访问它们,但我不清楚如何(或是否)可以使用 bindapply 来为这些外部定义的方法提供对 itemA 的访问权限,或者我是否还有其他机制不熟悉将使这成为可能。

没有。 Javascript 中的范围是词法的(基于代码的位置)。您不能更改已声明的函数的范围。

然而,您可以在调用它时将 itemA 作为参数简单地传递给 outerFunction。这是解决此类问题的通常方式和预期方式。

还有其他技术可以让事物更自动地访问一组变量,例如将值分配给更高但共享的范围,或者在公共对象上创建事物方法,所有对象都可以共享对实例数据的访问,但它从您对问题的描述来看,在这种情况下这些是否合适。

but I'm not clear on how (or if) it's possible to use bind or apply to give these externally defined methods access to itemA or if there's some other mechanism that I'm not familiar with that would make this possible.

.bind().apply() 不会以任何方式影响范围。它们使您可以控制函数的 this and/or 参数的值。如果感兴趣的变量在某个对象上可用,那么您可以使用 .bind().apply().call()this 的值设置为该对象并允许您的函数通过 this.property.

访问数据