3
class Hello{

    constructor(member) {
       this.member = member;

       this.name_function_map = {"print_member" : this.print_member};
    }

    print_member(){
        console.log(this.member);
    }
}

let h = new Hello(2);
h.print_member();
//=> works as expected


h.name_function_map["print_member"]();
//=> why is it h. member undefined

the output is:

2
undefined

can someone please enlighten me, why is calling the member function of Hello through a reference stored in a map any different than calling it directly?

And how may i work around that.

Tobias
  • 415
  • 1
  • 5
  • 5

1 Answers1

2

When you execute:

let h = new Hello(2);
h.print_member();

The this keyword inside the print_member method will be equal to h (the object instance). That is correct. But, when you execute:

h.name_function_map["print_member"]();

or equally

h.name_function_map.print_member();

the this keyword inside the print_member method will be equal to h.name_function_map, which is:

{"print_member" : this.print_member}

Obviously, this object does not have a member property, and that's why you are getting undefined.

mateleco
  • 519
  • 7
  • 15