ES6 class instance from string [duplicate] - javascript

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).

Related

Getting class name of instance and using it to create new instances in JS [duplicate]

This question already has answers here:
How to generate new instances of an object without the class?
(5 answers)
Closed 1 year ago.
I have many instances of different classes, I want to select any of them randomly (say inst1) and create a new instance of the class of selected instance (say cls1).
This is how I'm implementing it:
// getting class name of selected instance (say inst1), i.e. clsName is cls1
let clsName = inst1.constructor.name;
// use the class name obtained above to create new instance
let newInst = new clsName();
But it gives me error saying;
"Uncaught TypeError: clsName is not a constructor at HTMLDocument."
Is there a way to get around?
claName is a string, not a function. The constructor function is inst1.constructor, call that.
class Test {
constructor() {
console.log("constructing a Test");
}
}
inst1 = new Test();
cls = inst1.constructor;
inst2 = new cls;

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.

Mimicking Java-style inheritance in Javascript [duplicate]

This question already has answers here:
What is the reason to use the 'new' keyword at Derived.prototype = new Base
(6 answers)
Closed 7 years ago.
I'm trying to mimic Java-style class inheritance and I thought I'd gotten it. However, I'm having an issue that when I create multiple instance of the same Javascript class, all instances are sort of created the same.
Here is the situation.
I have a Javascript class called Screen:
function Screen(screenName) {
this.current = new DataResultSet(); // this is a java class
this.current.setScreenName(screenName);
}
Screen.prototype.GetScreenName= function() {
return this.current.getScreenName();
}
Screen.prototype.GetFieldValue= function(name) {
return this.current.getValue(name);
}
// some other functions that can be called that utilize the current object.
This is the inherited class:
function screenSub1() {}
screenSub1.prototype=new Screen("screenSub1");
screenSub1.prototype.GetID = function() { return GetFieldValue("ID"); }
// some other functions that can be called, specific to this class
Now, in my code, if I do
var obj = new screenSub1();
var obj2 = new screenSub1();
The underlying "current" object for both objects are the same! Is there anyway to get around this issue? Thanks!
Julia
As far as I know, you can't (at least not easily, maybe you could find some javascript library that mimics java-like inheritance). Java and Javascript are very different when it comes to inheritance. You can check here if You want to have further information on the subject : https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

How to instantiate class dynamically [duplicate]

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

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!

Categories

Resources