Call a javascript class object with variable

Viewed 46

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)

1 Answers

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)

Related