0

Below I have two member functions, sayHello and sayHi, that effectively do the same thing:

function Person (n) {
 this.name = n;
 this.sayHello = function() {console.log("Hello, my name is "+this.name);};
};
Person.prototype.sayHi = function() {console.log("Hi, I'm "+this.name);};

Jeff = new Person('Jeff');
Joe = new Person('Joe');

Jeff.sayHello() // returns "Hello, my name is Jeff"
Joe.sayHi() /// returns "Hi, I'm Joe"
I thought implementation-wise, they were identical, but now I'm starting to think that assigning the function to the prototype creates only one image of the function, whereas 'sayHello' is declared in the function, so a new image will be created every time a new Person object is created? Is that correct? Coming from the C++ world, I much prefer putting the declaration in the function, but don't want to do it if it results in bloat.
buttonsrtoys
  • 1,454
  • 1
  • 21
  • 36

1 Answers1

1

You are correct, declaring the function sayHello inside of the Person constructor function will create a new function every time that function is called, so it is wasting resource. However, this is not wasting any significant amount of resource and if it were to be an issue then there would be several other far more significant problems than simply that one function being redeclared.

As for best practice, it is mostly style. In general you want to stick to only using the prototype for extending though.

Travis J
  • 77,009
  • 39
  • 185
  • 250