Can I add a property dynamically in javascript?

Is it possible to add properties to an object at runtime? Everything seems to be in order, but are there any issues I should be aware of?

I use a third-party javascript API that has an object class that I created and added my own property after creating the instance, for example, 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; 
+6
javascript
source share
3 answers

Yes, this is called an increase in the object. This is a key feature of JavaScript.

+7
source share

In fact, you have two ways to do this in JavaScript:

  • add method or property to instance (this vehicle only)

     var myCar = new Car(1,"Nissan"); myCar.needsWork = true; 
  • add a method or property to a prototype car (all cars, even 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:

+7
source share

Yes

There is nothing wrong.

See the “Object Extension” section here: http://www.crockford.com/javascript/inheritance.html

+1
source share

All Articles