【问题标题】:Why doesn't "this" keyword work with static methods in a class in my code below?为什么“this”关键字不能与下面代码中的类中的静态方法一起使用?
【发布时间】:2018-08-24 13:00:59
【问题描述】:

我正在 Eloquent's JavaScript: Exercise Section -> Groups 做练习。我设法编写了代码,但我不明白为什么我的代码在使用 this 时不起作用。

我当前的代码:

class Group {
  constructor() {
    this.members = [];
  }

  has(value) {
    return this.members.includes(value);
  }

  add(value) {
    if (!this.has(value)) this.members.push(value);
  }

  delete(value) {
    if (this.has(value)) return this.members =
      this.members.filter(element => element != value);
  }

  static from(array) {
    let newGroup = new Group();
    for (let element of array) {
      newGroup.add(element);
    }
    return newGroup;
  }
}

我尝试将static from(array) {...} 更改为:

static from(array) {
  let newGroup = new Group();
  for (let element of array) {
    this.members.push(element);
  }
  return newGroup;
}

考虑到newGroup.add(element)this.members.push(element)比较相同,为什么后者在第二种静态方法中不起作用?

【问题讨论】:

    标签: javascript static this


    【解决方案1】:

    考虑到 newGroup.add(element) 和 this.members.push(element)

    不。静态方法内的this 指向类本身(Group),它不指向不存在的实例。这意味着您可以将其用作:

     let newGroup = new this();
     newGroup.members.push(element);
    

    【讨论】:

    • 我明白了。所以它并不指向newGroup。谢谢你的解释:-)!
    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 2018-07-05
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多