在es6类中怎么做`var self = this`? [英] how to do `var self = this` inside es6 class?

查看:470
本文介绍了在es6类中怎么做`var self = this`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nodejs中运行以下代码

I am running the below code in 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(); 抛出错误。

我们如何像 var self = this; 我们曾经在 es5 中做到这一点,以防止这种情况。

a(); throws the error.
How can we do like var self = this; as we used to do in es5 to prevent such a situation?

推荐答案


我们如何像以前在ES5中做的那样像 var self = this;

您可以像ES5一样完成 - ES6完全向后兼容:

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;
        };
    }
}

然而,这真的不是惯用的ES6(不在说 const 而不是 var )。你宁愿使用一个具有词法范围这个的箭头函数,这样你可以避免这个 self 变量完全:

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;
        };
    }
}

(甚至可以缩短为 this.toString =()=> this.x;

这篇关于在es6类中怎么做`var self = this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆