6

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;
1
  • 1
    Note, the Car function in your code is not a class. It is a constructor function. You may call it "pseudo-class". Commented Dec 1, 2010 at 17:01

3 Answers 3

13

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks i was aware of the prototype one i was just wondering if the 1st option was okay. If i could mark 2 answers i would. thanks for the info.
no prob, upvotes are actually better than accepts. Only upvotes get you tag badges :-)
P.Floyd I think it's better to attach non-function properties to the object itself (this.needsWork = true inside the constructor) rather then to the object's prototype.
@Šime Vidas sure, it's pretty much the same thing, only I come from a Java background and feel safer if I can actually see the properties I define in the class outline
8

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

Comments

1

Yes

There is nothing wrong with that.

See Object Augmentation here: http://www.crockford.com/javascript/inheritance.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.