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

标签 javascript ecmascript-6

我在 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/

相关文章:

javascript - 预加载图像 <img> 的首选方法是什么?为什么?

visual-studio-2013 - 如何在 Visual Studio 2013 中使用 ECMAScript 6 语法

javascript - 如何检查对象数组中的缺失值并使用特殊字符添加缺失值

javascript - 什么是 _interopRequireDefault ?

javascript - 将事件目录查询从 VBS 转换为 Javascript 以用于全局目录

javascript - Grails - 从 javascript 函数设置变量

javascript - jQuery/Javascript 检查鼠标是在窗口内还是窗口外

javascript - 当用户点击动态创建的链接时如何调用 JS 方法。 JQuery、ASP.NET MVC

javascript - 这真的被认为是 JavaScript 闭包吗?

javascript - 一个 promise 中的两次拒绝