繁体   English   中英

Javascript ES6(ES2015)/ Typescript:如何在静态方法中访问本地方法

[英]Javascript ES6(ES2015)/ Typescript: how to access local method inside static method

我基本上想访问静态“ bar”方法内的“ foo2”方法,但到目前为止,我只能访问“ foo1”和“ foo3”方法。 谁能教我如何访问非静态foo2方法。

let foo1 = () => {
    alert('foo1’);
  };

class ABC extends Component {

  static bar() {
      foo1(); //can work

      foo2; //not work with error "Can't find variable foo2"

      foo2(); //not work with error "Can't find variable foo2"

      this.foo2(); //not work with error "this.foo2 is not a function"

      this.foo2; //no error but no alert, basically nothing happen

      ABC.foo3() //can work
  }

  foo2 = () => {
      alert('foo2');
  };

  static foo3 = () => {
      alert('foo3');
  };

}

module.exports = ABC;

警告:不需要从静态方法访问实例方法,这可能会使其他开发人员感到困惑。 尽量避免使用它。 如果您确实使用它-请确保您的代码注释正确并说明其工作方式。

您要做的是将静态方法与对象的上下文绑定,该对象要从静态方法中调用。 您可以通过使用call方法调用它来做到这一点:

class ABC extends Component {
    static bar () {
      this.foo();
    }
    foo () {
      // function body
    }
}

let instance = new ABC();
ABC.bar.call(instance);

或使用bind如果您想传递回调等函数,则将其预绑定 ,可以这么说:

let instance = new ABC();
setTimeout(ABC.bar.bind(instance), 1000);

注意:默认情况下, this引用您的类,而不是该类的实例(在我们绑定该实例后,它将引用一个实例),因此,如果要从第一个静态方法中调用另一个静态方法,则要使用完整的类名。

static bar () {
  this.foo();
  ABC.someOtherStaticMethod();
}

还请注意:如果您使用Typescript,则在引用实例方法时会出现错误,因为默认情况下, this方法在您的静态方法中引用您的类。 要解决此问题,您可能需要将此类型转换为any

static bar () {
  (<any>this).foo();
}

在这里,您告诉Typescript编译器类似“假定this不是我们的类,但我们不知道的东西”之类的东西,只是为了消除编译时的错误。

您永远不能从静态方法(任何语言)访问实例方法。 只有一个静态方法,但是有多个实例,它如何知道要使用哪个实例( this )?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM