how to do `var self = this` inside es6 class?

前端 未结 2 1191
难免孤独
难免孤独 2020-12-08 19:38

I am running the below code in nodejs

this.x = \'global x\';
class Point {
    constructor(x) {
        this.x = x;
    }
    toString() {
        return thi         


        
相关标签:
2条回答
  • 2020-12-08 19:53

    If you don't want to create all your class methods inside the constructor as Bergi suggests (which seems ugly to me) then you can enable ES7 features and define your method using arrow syntax:

    class Point 
    {
        constructor(x) 
        {
            this.x = x;
        }
    
        toString = () =>  
        {
            return this.x;
        }
    } 
    

    This has the same effect as saying:

    constructor(x)
    {
        this.toString = this.toString.bind(this);
    }
    

    But it still doesn't allow you to access the dynamic this and the lexical this (self) in the same function. So this is not a complete answer.

    I hope someone can edit this answer to show how we can access both types of this in a class method without defining every method in the class constructor.

    0 讨论(0)
  • 2020-12-08 19:56

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

    0 讨论(0)
提交回复
热议问题