Search code examples
javascriptpropertiesthiscall

Using "call" properly in Javascript to access object properties


I'm new to Javascript, and despite having read several threads and tutorials online, I can't correctly use "call" in this example to access the property of the object

I know the problem is that when "b ()" is called, "this" is the global object, and I have to use the call (or apply) method to make sure that when "b" is called this is set to the object itself, but I can't find the error.

I know that arrow functions exist, and that there may be other approaches, but I want to understand what is the matter with this using of call. Thank you.

The code is

class Letter {
     constructor() {let a = "a";}
     b() {alert (this.a);} //can't access a. Prints "undefined"
     c() {this.b.call(this);}
}
let p = new Letter ();
p.c();

Solution

  • The a does not exist as a property of the object - it's a variable, an identifier visible within the constructor function, not an instance on an object.

    There's no good way to gain access to a variable declared in another scope like that. For what you're trying to accomplish, define a as a property of the instance instead.

    constructor() {
      this.a = 'a';
    }
    

    You won't need .call at all - just do this.b().