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:
Yea, this is called object augmentation. It is a key feature in JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With