有没有办法指定我想在 JS anon 函数中使用哪个“这个”,类似于 Java 的方式

Is there any way to specify which 'this' I want to use in a JS anon function, similar to how Java does it?

本文关键字:这个 方式 Java 类似于 函数 anon JS 有没有      更新时间:2023-09-26

我遇到过几次这个问题,我想知道是否可以在不将 anon 函数绑定到父对象的上下文中的"this"的情况下解决它。

这是我的情况:

我有一个类似数组的对象,我们称之为"numline",它实现了"each"方法。它包含在对象的另一个实例中,我们称之为"numtank"。当前代码如下所示:

function Numtank(numline) {
    this.numline = numline;
};
Numtank.prototype.charForElem(elem) {
    return "Number: " + elem;
}
Numtank.prototype.toString() {
    var str = "";
    this.numline.each(function(elem) {
        str += this.charForElem(elem); //But 'this' is called in the contex of the 'numline' instance, which dosen't (and shouldn't) have the charForElem class. 
    });
    return str;
}
var tank = new Numtank(arbatraryNumline);
tank.toString(); //Uncaught ReferenceError: charFromElem is not defined in numline

当我问"类似于Java如何做"时,我的意思是Java如何允许您将类名附加到"this"以指定使用哪个"this"。

有没有办法解决这个问题而不必将 anonomouns 函数绑定到这个?

通常做的是保存一个名为 self 的引用。这是最常见的做法。

Numtank.prototype.toString() {
  var self = this, str = "";
  this.numline.each(function(elem) {
    str += self.charForElem(elem);
  });
  return str;
}
您可以将

this的副本保存在另一个变量中。

var oldThis = this;

该变量对这些嵌套回调函数可见。