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

时间:2016-11-11 07:19:04

标签: javascript typescript ecmascript-6

我基本上想要在静态“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;

2 个答案:

答案 0 :(得分:3)

警告:不希望从静态方法访问实例方法,这可能会使其他开发人员感到困惑。尽量避免使用它。如果你确实使用它 - 确保你的代码得到很好的评论,并解释它是如何工作的。

您要做的是将静态方法与要从静态方法调用哪个方法的对象的上下文绑定。您可以使用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,则在引用instance-method时会出现错误,因为默认情况下,静态方法中的this会引用您的类。要解决此问题,您可能希望将此类型转换为any

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

在这里你告诉Typescript编译器类似&#34;假设this不是我们的班级,而是我们不知道&#34;只是为了摆脱编译时的错误。

答案 1 :(得分:2)

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

相关问题