0

Here is my problem, i have one object Car & theirs properties, i defined a method inside the object. but i think it is recommended to append this method to the object protytype, but why? what are the advantages and disadvantages? Thank you :)

What i did..

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

Recommended :

Car.prototype.getInfo = function() {
    return 'A ' + this.color + ' ' + this.desc + '.';
};
prakashapkota
  • 321
  • 2
  • 6
  • 1
    @bfavaretto No, I think this is more of what he's looking for: http://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype – Sethen Apr 01 '13 at 18:54
  • very related, but different. @SethenMaleno has it. – csturtz Apr 01 '13 at 18:55

1 Answers1

0

what you did results in every instance of Car having it's own copy of the getInfo method. Putting it on the prototype gives a that one function definition to every instance automatically.

csturtz
  • 6,380
  • 2
  • 24
  • 34