2
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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • You've got some mismatched braces in your code. Can you please fix them and properly indent the code? – Bergi Sep 06 '20 at 18:59
  • No, `this` in an object literal never points to the newly-constructed object. This has nothing to do with ES6 classes - `const obj = { key: this };` is the same (and `obj.key !== obj`). – Bergi Sep 06 '20 at 19:02

1 Answers1

1

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();
Thomas
  • 174,939
  • 50
  • 355
  • 478