相关疑难解决方法(0)

如何在es6类中执行`var self = this`?

我在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
Run Code Online (Sandbox Code Playgroud)

a();抛出错误.
我们怎样才能像var self = this;过去那样做es5 …

javascript ecmascript-6

32
推荐指数
2
解决办法
1万
查看次数

标签 统计

ecmascript-6 ×1

javascript ×1