this keyword in ES6 classes, only works when enclosing inside a function?

Viewed 71
class App {
    states = {
        key: this,
        awsm: {
            another: function() {
                console.log(this);
            }
        }
    render() {
        console.log(this); // Here "this" point to the class 
        this.states.awsm.another(); // "this" will point to immediate enclosing object awsm, which is fine

        console.log(this.states.key); // but Here "this" should point immediate enclosing object/class but not happening
    }
}

const myapp = new App();
myapp.render();

In render function, console.log(this) point to class because class is its immediate binding, simlarly console.log(this.states.key) should point to its immediate binding, which is states obj. but that not happening.

I think it will only look for its immediate binding, when this keyword is invoked from the inside of a function. please tell me if i am correct

1 Answers

This syntax (called public class fields) is experimental and not officially part of JavaScript yet; its proposal in TC39 does say:

Execution of initializer expressions

...

Scope: The instance under construction is in scope as the this value inside the initializer expression.

So what you've written should work if this feature eventually gets implemented according to the current draft proposal, but right now, I wouldn't depend on it. The September 2020 way of achieving the same result is to assign to this.x inside the constructor.

That said, on my browser (Firefox 80.0.1) this works and shows true:

class Foo {
  x = this;
  constructor() {
    document.write(this.x === this);
  }
}

new Foo();

Related