【问题标题】:JavaScript Classes: Accessing method from within an Object's function propertyJavaScript 类:从对象的函数属性中访问方法
【发布时间】:2020-12-03 11:22:35
【问题描述】:

我想知道是否有人知道我遇到的问题的解决方案。假设我们有以下 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。

【问题讨论】:

    标签: javascript class methods jsobject


    【解决方案1】:

    您需要使用arrow function 以避免创建新上下文,然后使用关键字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()

    【讨论】:

      【解决方案2】:

      试试this.makeNoise()

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

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

      【讨论】:

      • 这有同样的错误,因为function创建了一个新的this
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2022-01-16
      相关资源
      最近更新 更多