Jordan Davis Jordan Davis - 4 days ago 5
Javascript Question

Classes - 'this' vs 'self'

I'm using the new ES6 Classes and am having a hard time understanding why I can reference the

this
variable is one of the methods.

//CLASS

class Form{
constructor(){
var self = this;
}

assemble(){
log(self);
}
}


//CALLED

var form = new Form();
form.assemble();


//RETURN

window object (not the reference to the class object)

Answer

this isn't a variable. It's more like a hidden argument to functions.

You can't access self in your example because it's a local variable within the constructor, so it's not available to your assemble method.

You don't need self at all for your example, just use this:

class Form {
    assemble(){
        log(this);             // ***
    }
}
var form = new Form();
form.assemble();

If you were passing form.assemble to something that wouldn't guarantee to call it with the right this, you could define assemble as an instance function member instead, by defining it in the constructor; then it would close over self. But you don't need self for this in ES2015 and above; just use an arrow function, which closes over this:

class Form {
    constructor(){
        var self = this;
        this.assemble = () => {
            log(this);
        };
    }   
}
var form = new Form();
form.assemble();          // Works
var f = form.assemble;
f();                      // Also works

But odds are you don't need to do that.

Comments