我在 nodejs 中运行下面的代码
this.x = 'global x';
class Point {
constructor(x) {
this.x = x;
}
toString() {
return this.x;
}
}
var obj = new Point(1);
obj.toString();// 1 as expected
var a = obj.toString;// Here I can do something like var a = obj.toString.bind(obj); to get rid of the situation. But I am curious to know how can we write `var self = this`;
a();// TypeError: Cannot read property 'x' of undefined
a();
抛出错误。
我们如何像 es5
那样像 var self = this;
那样来防止这种情况发生?
最佳答案
How can we do like
var self = this;
as we used to do in ES5?
你可以像在 ES5 中那样做——毕竟 ES6 是完全向后兼容的:
class Point {
constructor(x) {
this.x = x;
var self = this;
this.toString = function() {
return self.x;
};
}
}
但是,这真的不是 ES6 的惯用语(不是在谈论 const
而不是 var
)。您宁愿使用具有词法范围 this
的箭头函数,这样您就可以完全避免使用此 self
变量:
class Point {
constructor(x) {
this.x = x;
this.toString = () => {
return this.x;
};
}
}
(甚至可以缩短为 this.toString = () => this.x;
)
关于javascript - 如何在 es6 类中执行 `var self = this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32583345/