0

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();
Paolo
  • 103
  • 6
  • 1
    You might like to read [*What is the scope of variables in JavaScript?*](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) Note that identifier (i.e. variable) resolution on the function scope chain is entirely different to property resolution on objects and their \[prototype\] chain, though they work in similar ways. – RobG Apr 04 '21 at 07:18

1 Answers1

2

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().

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320