How to instantiate class dynamically [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 8 years ago.
I have an array with names of constructors var arr = ['Class1', 'Class2', 'Class3'].
function Class1() {
this.name = 'class1';
}
Is it possible to dynamically create instances of these classes? I mean something like
var class1Object = new arr[0]();
I tried that but it isn't working (Uncaught TypeError: string is not a function).

functions defined in "global" scope are actually created on the window object, so you can do this (as long as the code is in the head of the page, and not scoped to something specific):
function Class1(){
this.name = 'class1';
}
var className = "Class1";
var c1 = new window[className]();
Live example: http://jsfiddle.net/vdf4W/

Previously answered in this post (Google: Dynamic Instantiation In JavaScript)
Dynamic Instantiation In JavaScript

Related

ES6 class instance from string [duplicate]

This question already has answers here:
Create object from class name in JavasScript ECMAScript 6
(8 answers)
Closed 4 years ago.
I try to setup an instance dynamically from a string. I've read many questions about it but the answers does not work for me.
It says it's possible to use window before the name to set the instance. It does not work.
class MyClass {
// Something useful
}
let params = {};
let name = 'MyClass';
let instance = new window[name](params);
I've also tried to do this without luck (throws error):
let instance = new window['MyClass'](params);
However, this works:
let instance = new MyClass(params);
Why can't I use window in this case? Any other ideas?
Only global variables are put into window automatically.
Create an object that maps from class names to classes:
const classMap = {
"MyClass": MyClass,
"MyClass2": MyClass2,
...
};
Then use classMap[name](params) rather than window[name](params).

Javascript: set object variable to inner object instance [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 6 years ago.
I'm trying to create a class to better organize my code, I decided to go the object literal route
var MyClass = {
}
I'm currently running into issues migrating some of my functionality though, previously I had global scope variables Channels for example set to an object instance. Is there a way to still do this in javascript within a class without moving the object into global scope?
var Prime = {
Channel: new __Prime__Channel(),
//The object in question
__Prime__Channel: function() {
this.Property = Value;
},
}
this throws
Undefined reference __Prime__Channel() at line 2
In global scope you could do
var Channel = new __Prime__Channel();
function __Prime__Channel() {
this.Property = Value;
}
without any errors
An object is no class, please ensure you're using the right terminology.
With an object literal it is not possible to do what you want, the only way is
var Prime = {
__Prime__Channel: function() {
this.Property = Value;
}
}
Prime.Channel = new Prime.__Prime__Channel();
However, maybe an object literal is the wrong pattern anyway. If you want to avoid global variables, look into the module pattern and IIFEs.

When have have I to use var before a variable name in JavaScript? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 7 years ago.
I know that in JavaScript I can define a variable in this way:
menuItems = new Array();
or putting the var before the variable name, so:
var menuItems = new Array();
Exist some difference between these two versions ? What change?
Tnx
When you don't use var it goes into the global scope (in browser into the window object, in node into the global object). So your first one is equivalent to window.menuItems = ... in a browser.
This is not usually good because you are polluting the window object potentially overwriting or leaving menuItems to be overwritten by other code.
In the 2nd case it goes into a variable that exists in the scope of the function that wraps that bit of code and any other functions inside it. So
...
function() {
... bits of code except creation of a function ...
var menuItems = new Array();
... bits of code ...
}
// menuItems is undefined here so whatever you do on something called menuItems here actually acts on a different variable menuItems
http://speakingjs.com/es5/ch16.html is an excellent link if you want to delve into details.

Convert static object to dynamic [duplicate]

This question already has answers here:
Adding Prototype to JavaScript Object Literal
(5 answers)
Closed 9 years ago.
If I have an object like this:
var obj = {};
I can't extend it because it hasn't got any prototype.
Is there any way to convert this object to dynamic so that it's possible to extend it and use new keyword. Something like:
obj.prototype.property = 'value';
var newobj = new obj;
That has nothing to do with static or dynamic.
You can only use the new operator on functions, not objects.
You cannot turn an object into a function; you need to create it as a function in the first place.
the only way is the following:
var obj = function () {};
because you can only use the new keyword with constructor function. That's it!

Creating "static" members in a javascript object [duplicate]

This question already has answers here:
Static variables in JavaScript
(43 answers)
Closed 8 years ago.
Is there a way to create "static" members in a JS Object?
function Person(){
}
Person.prototype.age = null;
Person.prototype.gender = null;
I would like to add personsCount as a static member, is that possible?
Sure, just add Person.personsCount without the prototype
Common practise is to make such "static members" properties of the constructor function itself:
function Person() {
Person.count++;
}
Person.count = 0;

Categories

Resources