S
S
Svyatoslav Khusamov2015-10-29 15:51:43
JavaScript
Svyatoslav Khusamov, 2015-10-29 15:51:43

How to create objects dynamically in JavaScript?

I know this way:

var classname = "Number";
var num1 = eval(`new ${classname}()`);

The IDE swears at him: "eval can be harmful".
Is there any more correct way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Kitmanov, 2015-10-29
@khusamov

new (window || global)[className](); // window в браузерах, global в node

S
Scribblex, 2015-10-29
@Scribblex

I will suggest this option:
function ClassName () {
// ...
}
var className = new ClassName();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question