vlio20 vlio20 - 2 months ago 6
Javascript Question

JavaScript why the 'this' isn't binded correctly

Take a look at this fiddle:

https://jsfiddle.net/2aLht10r/1/
enter image description here

You can see that I am getting

undefined
when what I want is to get
B
.
For some reason, the this in line 11 is
undefined
where it should be the this of the
a
object created in line 17 (within class
B
).

What is wrong with my code?

Here is the fiddle code:

class A {
selector;
ui = {
selector: `${this.selector} aaa`
}

constructor(selector) {
this.selector = selector;
}

clog = console.log.bind(null, this.ui.selector)
}

class B {
selector;
ui = {
a: new A('B')
}

print = this.ui.a.clog.bind(this.ui.a);
}

new B().print();

Answer

The ordering of operations is tripping you up.

class A {
  selector;
  ui = {
    selector: `${this.selector} aaa`
  }

  constructor(selector) {
    this.selector = selector;
  }
}
console.log(new A("thing").ui.selector)

prints undefined aaa as you said because it is equivalent to this:

class A {
  constructor(selector) {
    this.ui = {
      selector: `${this.selector} aaa`
    };

    this.selector = selector;
  }
}
console.log(new A("thing").ui.selector);

so your ui property stores this.selector + 'aaa' before it has been assigned the value passed into the constructor.

Perhaps you'd be better off doing this:

class A {
  ui = {
    selector: null,
  };

  constructor(selector) {
    this.ui.selector = `${selector} aaa`;
  }
}
console.log(new A("thing").ui.selector)