Sig
Sig

Reputation: 5986

Instantiate an object from the class name string

I'm trying to dynamically instantiate a JS object according to the selected option. My HTML looks like

<select class="klass">
  <option value="Klass1">1</option>
  <option value="Klass2">2</option>
  <option value="Klass3">3</option>
</select>

And here my JS (so far)

let elements = [1,2,3]
let klass_name = document.querySelector('.klass').value
let klass = new ???(elements)
console.log(klass.params())



export default class Klass1 {
  constructor(elements) {
    this.elements = elements
  }

  params() {
    return "lorem"
  }
}

export default class Klass2 {
  constructor(elements) {
    this.elements = elements
  }

  params() {
    return "ipsum"
  }
}

export default class Klass3 {
  constructor(elements) {
    this.elements = elements
  }

  params() {
    return "this is very comPLEex@"
  }
}

What should I replace ??? with?

It'd be great if I don't have to predefine all the possible option in the JS.

I'm not trying to change the class but to instantiate an object of such class.

Upvotes: 0

Views: 78

Answers (2)

Murtaza Hussain
Murtaza Hussain

Reputation: 4315

It is building a dictionary where you have the value you retrieve from the select associated to the class you want to create. So Klasses[klass_name] returns the class you want to create.

const Klasses = {
  Klass1: class Klass1 {
    constructor(elements) {
      this.elements = elements
    }

    params() {
      return "1"
    }
  },
  Klass2: class Klass2 {
    constructor(elements) {
      this.elements = elements
    }

    params() {
      return "2"
    }
  }
};

let elements = [1, 2, 3]
let klass_name = document.querySelector('.klass').value
const klass = new Klasses[klass_name]();
console.log(klass.params());
<select class="klass">
  <option value="Klass1">1</option>
  <option value="Klass2">2</option>
  <option value="Klass3">3</option>
</select>

Upvotes: 2

Pierre GUILLAUME
Pierre GUILLAUME

Reputation: 449

Instead of creating a function for each klass, you could use this : var x = document.getElementById("mySelect").value;

x will contains the value of your option (here : klass1, 2 or 3) then you just have to get the last character (or to change the value of the option if possible)

Upvotes: 0

Related Questions