Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a new object in javascript based on a type-string?

How do I create a new object in javascript based on a variable type-string (containing the name of the object)?

Now I have: (with more tools coming the list will get longer...)

function getTool(name){
  switch(name){
    case "SelectTool":
      return new SelectTool();
      break;
    case "LineTool":
      return new LineTool();
      break;
    case "BlurTool":
      return new BlurTool();
      break;
    case "PointerTool":
    default:
      return new PointerTool();
      break;
  }
}

And defined my tools like:

PointerTool.prototype = new Tool;
PointerTool.prototype.constructor = PointerTool;
function PointerTool(){
  this.name = "PointerTool";
}
PointerTool.prototype.click = function(x, y){
  info("You clicked at: "+x+", "+y);
}

I would like to get ride of the (growing) switch statement, it seems 'wrong'.

like image 824
Dribbel Avatar asked Dec 05 '10 19:12

Dribbel


People also ask

How do you turn a string into an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Can I create object with string?

There are two ways to create a String object: By string literal : Java String literal is created by using double quotes. For Example: String s=“Welcome”; By new keyword : Java String is created by using a keyword “new”.

What are 3 ways to create an object in JS?

Creating a JavaScript Object There are different ways to create new objects: Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type.


1 Answers

function getTool(name){
  return ( typeof window[name] === 'function' ) ? 
                                    new window[name]() : {/*some default*/};
}

Assumes PointerTool constructor is defined in the global window namespace. Replace that with whatever namespace you're using.

like image 196
user113716 Avatar answered Oct 27 '22 00:10

user113716