Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么';";这";关键字在下面我的代码中的类中使用静态方法?_Javascript_Static_This - Fatal编程技术网

Javascript 为什么';";这";关键字在下面我的代码中的类中使用静态方法?

Javascript 为什么';";这";关键字在下面我的代码中的类中使用静态方法?,javascript,static,this,Javascript,Static,This,我正在做这个练习。我成功地编写了代码,但我不明白为什么我使用this时代码不起作用 我当前的代码: class Group { constructor() { this.members = []; } has(value) { return this.members.includes(value); } add(value) { if (!this.has(value)) this.members.push(value); } delet

我正在做这个练习。我成功地编写了代码,但我不明白为什么我使用
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) {
  let newGroup = new Group();
  for (let element of array) {
    this.members.push(element);
  }
  return newGroup;
}
考虑到
newGroup.add(element)
this.members.push(element)
相对相同,为什么后者在第二个静态方法中不起作用

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

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

 let newGroup = new this();
 newGroup.members.push(element);
考虑到newGroup.add(元素)和this.members.push(元素)

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

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

我懂了。所以它没有指向
newGroup
。谢谢你的解释:-)!我懂了。所以它没有指向
newGroup
。谢谢你的解释:-)!