0

Consider this code example:

function Person(config) {
    this.name = config.name;
    this.age = config.age;
}

Person.prototype.getAge = function() {
    return this.age;
};

var tilo = new Person({name:"Tilo", age:23 });
console.log(tilo.getAge());

Rather than defining getName() as an appendage to the constructor's prototype property, it seems to me it could be defined within the constructor to achieve the same thing? Is there any useful difference? In other words, does doing it one way or the other have any particular implementation advantage?

  • defining methods in the constructor subverts the entire OO system, makes them all ad-hoc, makes it impossible to tell at a glance (for either a human or a machine) what the methods even _are_, etc. – Eevee Sep 19 '15 at 04:06

1 Answers1

0

The constructor will create a new instance of that function with each invocation. Putting it on the prototype will save memory.

Josh C.
  • 4,303
  • 5
  • 30
  • 51