2

I am new to Object Orientated Javascript and have created an object called Foo (based on a class) with an object called buttons. To call buttons I can type

console.log('foo log: ',foo.buttons)
//foo log:  testButton1

I want to replace call foo.buttons by replacing foo with a variable called myVar. It must be simple but none of the solutions I can see for this seem to work in my situation. I think there may be a scope problem but don't understand what it is.

WHAT I HAVE TRIED ALREADY

class TestClass {
  constructor(
    button)
    {this.button = button}
}

const myVar = 'foo'
const foo = new TestClass ('testButton1')

console.log('foo log: ', foo.button)
//foo log:  testButton1

console.log('myVar: ', myVar)
//foo




console.log('Attempt1: ', [myVar].button)
//Attempt1:  undefined

//console.log('Attempt2: ', [myVar]button)
//     failed to compile

console.log('Attempt3: ', myVar.button)
//Attempt3:  undefined

console.log('Attempt4: ', (myVar).button)
//Attempt4:  undefined

console.log('this:', this)
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
Benny
  • 103
  • 2
  • 12
  • "*I want to replace call foo.buttons by replacing foo with a variable called myVar*" - why? – Bergi Jul 20 '20 at 09:48
  • 1
    If you declare it as a global variable using `var` you could use `window[myVar]`. As long as your scope is `window` or whatever you assing it to. – Lain Jul 20 '20 at 09:53
  • I have a prop that is comming from another component and I want that prop myVar to be used to find the object that relates to it so I can use that in the program later on – Benny Jul 20 '20 at 09:56
  • I don't know who closed it, so I can't give a proper answer. In my opinion, best approach would be to map your cases. Something like: ```const options = { foo: new TestClass('testButton1'), bar: new TestClass('testButton2'), baz: new TestClass('testButton3') } ```. Then you get it with ```options[myVar].button``` – Tzahi Leh Jul 20 '20 at 10:01

1 Answers1

1

You can use eval, but this could be dangerous.

class TestClass {
  constructor(
    button)
    {this.button = button}
}

const myVar = 'foo'
const foo = new TestClass ('testButton1')

console.log(eval(myVar).button)
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • thanks! I looked up eval and it says using strings to invoke object is a bad idea. This will get me by for the moment but I'll look into alternative was of achieving my aim. Thanks – Benny Jul 20 '20 at 10:00