ES6 creating new instance with reflection [duplicate] - javascript

This question already has answers here:
Create an instance of a class in ES6 with a dynamic name? [duplicate]
(2 answers)
Closed 7 years ago.
I have a use case where I need to persist the name of a given class in a cookie so that I can create an instance of it later when the client returns. I would like to be able to do something like this:
class MyClass {
}
var a1 = new MyClass()
var className = a.class.name()//like in Java..
var a2 = Class.forName(className).newInstance();
Is this possible in ES6? Specifically I am looking for some way to get the name fo the class as a string,

You should be able to get the name of the class by calling a1.constructor.name1
Since classes are really fancy syntax for functions, if the class exists on the window object you could probably then do something like var a2 = new window[className](); but that really depends what scope you are working in.

Related

use `this[]` to get private property inside the class in javascript [duplicate]

This question already has answers here:
js dynamically access private fields (properties/members)
(5 answers)
Can I set a private class field using a variable as identifier? How?
(1 answer)
How to get access to private field via square brackets in JavaScript
(2 answers)
Closed last year.
It's acknowledge that we can access a property of an object by two ways :foo.bar and foo['bar'], but when I use the new feature # to declare a private member in class, it won't work properly:
class FooBar{
constructor(){}
testCall(name){
this[name]()
}
bar(){console.log(1)}
#bar(){console.log(2)}
}
let foo = new FooBar();
foo.testCall('bar'); //this line works properly
foo.testCall('#bar'); //Uncaught TypeError: this[name] is not a function
Can someone please tell how can I modify it to make the code work properly

The use of prototype in javascript (comparsion with constructor and how to use it) [duplicate]

This question already has answers here:
Javascript when to use prototypes
(6 answers)
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 4 years ago.
why should i use prototypes is js?
for example if i want to create a constructor like:
var Person = function(name, yearOfBirth){
this.name = name;
this.yearOfBirth = yearOfBirth;
this.calculateAge = function(){
console.log(2018-this.yearOfBirth);
}
}
is better to use prototype for functions like:
var Person = function(name, yearOfBirth){
this.name = name;
this.yearOfBirth = yearOfBirth;
}
Person.prototype.calculateAge = function(){
console.log(2018-this.yearOfBirth);
}
should i use prototype also for props like name etc?
Can someone tell me the differences between using or not prototypes and what's the best use of it?
Thanks
EDIT: this is the best answer that i've found: https://hackernoon.com/prototypes-in-javascript-5bba2990e04b
Prototype properties are shared across all instances of the constructor function.
In your case the calculateAge function need not be required as a separate instance for all objects that you create out of Person and hence can be moved to Prototype, whereas properties like name and yearOfBirth need a separate instance for each object that you create from Person
You can define Prototypes properties on constructor functions when you wish to create a common property shared across all instances of the function.

Create Javascript classes dynamically [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Create object from class name in JavasScript ECMAScript 6
(8 answers)
Closed 4 years ago.
I have a question which shouldn't be to difficult, but I've been spending days and can't seem to find the answer. All the solutions I found didn't help me, they all threw errors.
I made a Class in Javascript and want to create a new instance dynamically, so that I can instantiate multiple classes depending on the parameter in a function. It doesn't seem te work, and I wonder why.
settings.js and main.js are loaded via <script> tag in the HTML file, with settings.js being loaded first.
main.js
let myClass = new settings(); // Works
let myClass2 = test('settings'); // Error: Uncaught TypeError: param is not a constructor
function test(param){
return new param();
}
settings.js
class settings{
constructor(){
console.log("works");
}
}
Thanks for any help!

How to create the instance of the class by its string name? I tried to use `window` for these purposes also. [duplicate]

This question already has answers here:
How do I make JavaScript Object using a variable String to define the class name?
(10 answers)
Get global variable dynamically by name string in JavaScript
(6 answers)
Closed 5 years ago.
JS6, Browser
How to create the instance of the class by its string name? For example I have a string Foo and I need to create an instance of Foo class. I don't want to write such construction:
let className = getClassName(); // returns 'Foo', `Stuff` or other
...
let item = null;
if(`Foo` == className){
item = new Foo();
}
else if(`Stuff` == className){
item = new Stuff();
}
UPD
I try to get access to my class constructor through the window object but I have the problem: it returns undefined. But my class exists and browser knows it:
What you are trying to do is what you should do, in my opinion. This is a standard way of instantiating objects when the type of object is known at runtime, and is called the Factory Method Pattern.
You should avoid duplicating this everywhere in your code by using a factory object that will encapsulate the object creation. This factory object will have a method that will take the type name as its parameter.
Please use google: Instantiate a JavaScript Object Using a String to Define the Class Name
var myObject = window[classNameString];
P.S. I copy pasted your title of question and added javascript in front.

About js objects [duplicate]

This question already has answers here:
Constructors in JavaScript objects
(19 answers)
Closed 8 years ago.
my English is not so good, but i try to explain my self clear.
I just started learn JS objects and stumbled upon the problem that i can't understand.
I got a simple object like
var cars = {
doors: 4,
wheels: 4
}
and when i trying to create an object like this:
var Opel = new car()
I got an error Uncaught TypeError: object is not a function
And when i do it like this :
Opel = Object.create(cars)
all going fine.
And when i writing a an Object like this :
function cars() {}
a method to declare the object with new, work correctly.
I can't understand what the difference between thous two type of writing the objects.
Thanks for advice.
You didn't understand prototyping correct.
To define a class you create a simple function, like:
function Car(){
this.doors = 4; //For instance, not really necessary
}
You can set properties on this in the function.
Then you define a prototype, every object of class "Car" will have all this properties (and "methods"):
Car.prototype = {
doors: 4, //we don't need to set this again if we already did in the constructor, but I'll leave if it anyway
wheels: 4
}
Please see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript for more.

Categories