0

我想知道是否有可能有人知道我遇到的问题的解决方案。假设我们有以下 JavaScript 类:

class foo {

    // Class Method.
    makeNoise() {
        console.log("bar");
    }

    // Class Object
    classObject = {
        makeASound: function() {
            makeNoise();
        }
    }
}

现在,如果我打电话给:

var foo = new foo();
foo.classObject.makeASound();

我会得到一个错误,说 makeNoise 没有定义。使用“这个”。不起作用,因为在这种情况下,它会在 classObject 中查找函数,因此会抛出“不是函数”错误。无论如何都可以从对象的函数中访问 makeNoise 。

4

2 回答 2

2

您需要使用箭头函数以避免创建新上下文,然后使用关键字this才能makeNoise正确访问类的方法

class Foo {
  makeNoise() {
    console.log("bar");
  }
  classObject = {
    makeASound: () => { // arrow function for lexical scope
      this.makeNoise(); // using `this` to refer to the Foo method
    },
  };
}

如果愿意,您也可以使用Function.bind()

于 2020-08-13T15:17:23.987 回答
-1

尝试this.makeNoise()

classObject = {
    makeASound: () => {
        this.makeNoise();
    }
}

更新:如果我们对 使用箭头函数makeASound,我们可以保留this与父类的绑定。GMaiolo 的回答是正确的。

于 2020-08-13T15:17:04.920 回答