How can we do like var self = this;
as we used to do in ES5?
You can do it exactly like you did in ES5 - ES6 is completely backward-compatible after all:
class Point {
constructor(x) {
this.x = x;
var self = this;
this.toString = function() {
return self.x;
};
}
}
However, that's really not idiomatic ES6 (not talking about const
instead of var
). You'd rather use an arrow function that has a lexical-scoped this
, so that you can avoid this self
variable completely:
class Point {
constructor(x) {
this.x = x;
this.toString = () => {
return this.x;
};
}
}
(which could even be shortened to this.toString = () => this.x;
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…