【发布时间】: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