0

I searched in google but i could not find anything

test.js

class Hero(){
 heroVar = 'hero1'
 hero1() {
    alert('I am Hero 1');
 }
 onClick(){
    this[this.heroVar](); //this.heroVar value gets substituted with hero1
 }
}

Is there any better use case,how this this[this.heroVar](); works,please explain, does this also adds '.' in between 'this' and '[]' like this.hero1()

  • There are two ways to access a property of an object: dot notation (`foo.bar`) and bracket notation (`foo[...]`, where `...` can be any expression). In this case the value that `this.heroVar` resolves to is used as property name for accessing `this`. – Felix Kling Oct 06 '20 at 08:29
  • there is two ways of accessing a property in an object : . and [] By doing this this[] you will eval the value passed, so here you give a string which equals the function that you can directly execute. `this[this.heroVar]();` `this` = current object, `[]` accessing property/function, `this.heroVar` is a string which equal the name of your function, `()` you execute the function. – ThomasP1988 Oct 06 '20 at 08:31

1 Answers1

0

In Javascript class is an Object so

class Hero(){
 heroVar = 'hero1'
 hero1() {
    alert('I am Hero 1');
 }
 onClick(){
    this[this.heroVar](); //this.heroVar value gets substituted with hero1
    // equal with this['hero1']()
    // equal with hero1()
 }
}
Anhdevit
  • 1,926
  • 2
  • 16
  • 29