【问题标题】:Access class scope within static function ES6在静态函数 ES6 中访问类范围
【发布时间】:2018-04-10 02:30:22
【问题描述】:

如何使用类的静态函数访问this 范围?我在这里遗漏了什么吗?

class Example {

  constructor() {
    this.name = 'Johan';
  }

  static hello(){

    // How to access `this` scope here in the static

    Example.name; // Undefined
    this.name; // Undefined
  }

}

【问题讨论】:

  • this in hello 是类本身
  • 这里的前提是有缺陷的——你在一个类的实例中设置this.name,而静态方法本身就没有。
  • 我理解这一点,但使用 Example.name 访问 this.name 会导致未定义。
  • name 是一个实例变量。要访问它,您必须创建一个实例(在静态方法中)。 Example.name 暗示 name 是类的静态成员,显然不是。
  • 你能举个例子吗?

标签: javascript es6-class


【解决方案1】:

评论者是正确的,this 在静态类方法的上下文中就是类本身。

当您使用new 创建类的实例 时,该实例 是它自己的this。您可以通过this访问实例上的属性和方法。

请看下面的例子:

class Example {

  constructor() {
    this.name = 'Johan';
  }

  static hello(){
    console.log(this);
    console.log(this.name);
  }

}

Example.hello();  // logs out the above class definition, followed by the name of the class itself.

let x = new Example();
console.log(x.name);  // logs out 'Johan'.

x.hello(); // x does not have `hello()`.  Only Example does.

【讨论】:

  • 谢谢,但我需要在类的静态函数内而不是在外面运行这个实例。这可能吗?在static hello() 中的含义我需要访问this.name 而无需在课堂之外获得它。
  • @Nicos:你想要的没有意义。如果静态调用方法,则没有实例,因此没有this。 Javascript 无法为您确定该类的哪个实例是预期的。因此,与其用自己的方式解决这个问题,不如尝试找出为什么您要这样做,然后尝试以不需要这种 hack 的不同方式解决您的问题。
  • 谢谢,这就是我想知道的全部内容。
  • this 在静态类方法的上下文中是……”,不,不是类prototype本身。
猜你喜欢
  • 2017-04-07
  • 2016-08-13
  • 1970-01-01
  • 2015-02-06
  • 2016-03-17
  • 2021-08-11
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
相关资源
最近更新 更多