Unable to cast object to class in JavaScript ES6 - javascript

I am creating a map to which I am adding a custom class object,
var member_map = {};
var memberAction = new MemberActions(members.data[i].id, members.data[i].name);
member_map[memberAction.id] = memberAction;
Now when I try to get back a MemberActions object from the map using an ID, i get an Object rather than a MemberActions object.
var memberAction = member_map[fetch_id];
How do I cast the object?
EDIT:
My class defn:
class MemberActions {
constructor(id, name) {
this.id = id;
this.name = name;
}
}

JS doesn't have such a thing as object casting.
When you say you've got an Object this may mean when you try to console.log(memberAction) you get told that it's an Object - however it doesn't mean that isn't a MemberActions object.
To check the name of it, try:
console.log(memberAction.constructor.name)
memberAction.constructor should also contain the constructor you've defined.

Related

If I create a new object in JavaScript, isn't new memory allocated for all the properties of the function?

I recently read that using private method is bad because they are very memory inefficient because a new copy of the method would be created for each instance. In the example given, how is dispalyIncreasedSalary more efficient than increaseSalary?
var Employee = function (name, company, salary) {
this.name = name || ""; //Public attribute default value is null
this.company = company || ""; //Public attribute default value is null
this.salary = salary || 5000; //Public attribute default value is null
// Private method
var increaseSalary = function () {
this.salary = this.salary + 1000;
};
// Public method
this.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
};
};
// Create Employee class object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);
In the following example is this.dispalyIncreasedSalary reused for all objects?
No. You are binding it to this. So each gets it's own copy of that. That is what an instance member means. They bind to instance and not to Class/Object.
What about this.name etc. properties?
Same.
Aren't the this.propName not copied for all the instances?
If that happens all instance see the same value and that's a big NO.
You are correct that it is wasteful/inefficient to duplicate what could be a shared function for each instance.
You should investigate how JavaScript prototypes work: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
So shared methods would be placed onto every object and shared like this:
Employee.prototype.dispalyIncreasedSalary = function() {
increaseSalary();
console.log(this.salary);
}

Is it possible to add value to a new property of an object in js?

In js I have created an object. I want to add a new property to the object's prototype and the property will be different from instance to instance.
Now to add value I used get. But it gives me error. I have added the code below.
How can I accomplish this thing?
I have googled this. And all I have learned is by get they add value to an existing property. But I want to add value to the new property and that will vary instance to instance.
var computer = function (name, ram) {
this.name = name;
this.ram = ram;
};
Object.defineProperty(computer.prototype, "graphic", {
set: function graphic(value) {
this.graphic = value;
},
get: function graphic() {
return this.graphic;
},
});
var vio = new computer("sony", "8gb");
vio.graphic = "gtx980";
console.log(vio.graphic);
The error massage:
enter image description here
Rereading your question, I'll answer the actual concern:
When you put things on the prototype, they are shared between all instances (as though you add them to the class in a classical language like Java).
When you put things on this, they are only accessible for the specific instance.
The following works, without setters or getters:
function Computer(name, ram) { // Please use Capital names for constructors
this.name = name;
this.ram = ram;
};
let vio = new Computer('sony', '8gb');
vio.graphic = 'gtx980';
The graphic property will only exist for the instance held in vio, not every computer instance out there.
If, on the other hand you were to do this:
function Computer(name, ram) {
this.name = name;
this.ram = ram;
}
Computer.prototype.graphic = 'gtx980';
// All instances of Computer will now have a .graphic with the value of 'gtx980'.
The reason you're getting the error is that you define a setter for graphic, in it, you're trying to assign to graphic which invokes the setter for graphic which tries to assign to graphic which invokes.... you get the point.
The solution is to change the name of the actual variable (to, say _graphic).
var computer = function (name, ram) {
this.name = name;
this.ram = ram;
};
Object.defineProperty(computer.prototype, "graphic", {
set: function graphic(value) {
this._graphic = value;
},
get: function graphic() {
return this._graphic;
},
});
var vio = new computer("sony", "8gb");
vio.graphic = "gtx980";
console.log(vio.graphic);
Note that JS doesn't really have private variables. You won't be able to prevent someone from changing _graphic.

Array of custom object in JavaScript

I'm new to JavaScript and ran into an issue creating an array of custom objects.
I'm trying to apply the MVC concept. So in my Model I try to create a 'Node' object like this:
interFace.createNode = function(name) {
debug('createNode');
this.name = name;
this.childNodes = [];
...
return this
};
In my Controller I have a function where I create new nodes dynamically and add them to the childNodes array of the parent node like so:
parent_node.childNodes.push(Model().createNode("Node " + getNodeCount());
Push always returns 1, a subsequent call to length always 0. If I just push an integer value and not a node object the code works fine and the array grows as expected.
Basically what I want is to create Node-objects dynamically (like new Node() in Java) and add those objects to an array of Nodes. But I suspect that my understanding of objects in JS is flawed by my experience in OO programming.
Any help on how to resolve this issue is greatly appreciated.
Thanks in advance.
I believe you want something like this:
interFace.createNode = function(name) {
debug('createNode');
var node = {};
node.name = name;
node.childNodes = [];
...
return node;
};
or, something like this:
interFace.createNode = function(name) {
debug('createNode');
return new interFace.Node(name);
};
interFace.Node = function(name){
this.name = name;
this.childNodes = [];
...
}
There are several ways of creating objects in JS use of OOP principles such as prototypes and literals, etc.
With regard to your question and the task you are going to achieve, following is a literal wrapper where you can populate a node object in static nature.Since you are invoking this method dynamically to create nodes.
var nodeHanlder = {
create : function(name){
return {
name : name,
childNodes : []
}
}
};
var node = nodeHanlder.create("Node 1");
this will return object...
to access properties,
//node.name;
//node.childNodes;

use of prototype in javascript

I am learning prototype in JavaScript and this is the code I am trying -
<script>
function employee(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var trialcoder = new employee('trialcoder', 26, 'M');
//employee.prototype.salary = null;
trialcoder.salary = 19000;
document.write("salary is "+ trialcoder.salary);
</script>
My thoughts- To add another property we need to use prototype like - employee.prototype.salary = null; so on un commenting this line, I was expecting an error but it was not..let me know where I am wrong in the prototype concept.
Code Source - http://www.w3schools.com/jsref/jsref_prototype_math.asp
Your code is correct, because when you called
var trialcoder = new employee('trialcoder', 26, 'M');
You got an object instance of employee and just like any other object you can add properties to your trialcoder object like
trialcoder.salary = 19000;
In this case, the salary property is only available to your trialcoder object and if you make another instance of employee like var another = new employee() you have no salary property in another object, but, if you do something like
function employee(name, age, sex) { //... }
employee.prototype.salary = 19000;
and then make instances like
var anEmp = new employee();
console.log(anEmp.salary); // 19000
Make another instance
var newEmp = new employee();
console.log(newEmp.salary); // 19000
if you want, you can
newEmp.salary = 10000;
console.log(anEmp.salary); // 10000
Which means, when you add a property in the prototype of a constructor (employee) then every object instance can share the same property and after making an instance from the constructor, you can change the property of an instance but this won't effect other instances. Hope it's clear enough now.
Your code is right and you will not receive error because using prototype your setting property salary of class employee and after creating an object of your class ur are setting the property for that specific object,if you create another object you can set its property salary too
If you set property using prototype then all objects of that class will share that (salary) property .

Can I add a property dynamically in javascript?

Is it okay to add properties to an object at runtime? It seems to run okay but are there any issues I should be aware of?
I'm using a 3rd party javascript API which has an object class, which I've instantiated and added my own property to after instantiation, like the code below:
For example can I do this:
var Car = function (id, type) {
this.id = id;
this.type = type;
};
var myCar = new Car(1,"Nissan");
// CAN I DO THIS: (needsWork not a property of object Car)
myCar.needsWork = true;
Actually, you have two ways to do that in JavaScript:
add a method or property to an instance (this car only)
var myCar = new Car(1,"Nissan");
myCar.needsWork = true;
add a method or property to the car prototype (all cars, even already existing ones)
var myCar = new Car(1, "Nissan");
var biggerCar = new Car(2, "Hummer");
Car.prototype.needsWork = true;
alert( myCar.needsWork && biggerCar.needsWork
? "We need work"
: "Something wrong here"
);
Reference:
Object.prototype
Yea, this is called object augmentation. It is a key feature in JavaScript.
Yes
There is nothing wrong with that.
See Object Augmentation here: http://www.crockford.com/javascript/inheritance.html

Categories

Resources