Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a property dynamically in javascript?

Tags:

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;
like image 835
capdragon Avatar asked Dec 01 '10 16:12

capdragon


2 Answers

Actually, you have two ways to do that in JavaScript:

  1. add a method or property to an instance (this car only)

    var myCar = new Car(1,"Nissan");
    myCar.needsWork = true;
    
  2. 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
like image 150
Sean Patrick Floyd Avatar answered Sep 28 '22 05:09

Sean Patrick Floyd


Yea, this is called object augmentation. It is a key feature in JavaScript.

like image 30
Šime Vidas Avatar answered Sep 28 '22 06:09

Šime Vidas