2

As in the topic, when we are defining a future object (for ex.):

function Person(name) { 
    this.sayName = function() { 
        console.log(this.name);
    };
}

Person.prototype.sayName = function() { 
    console.log(this.name);
};

both methods will be available for newly created object. The only difference is that the 'this' expression will create this method for every instance and with 'prototype' it will be shared in memory (as far as I know). I've faced both expressions and what is interesting the first one is far more popular than the second one.

My question is... what is the proper way in JavaScript the first or the second ? ( I know both works but... what is the code engineering standard and why ).

Oskar Szura
  • 2,469
  • 5
  • 32
  • 42
  • 2
    Check sidebar of related questions. http://stackoverflow.com/questions/6918509/this-method-function-vs-obj-prototype-method-function?rq=1 – elclanrs Aug 21 '13 at 07:46

1 Answers1

1

The proper way is the second one (what else would you need prototypes for?).

The advantage of the first approach is ability to get something like private variables: if you declare a local variable in constructor (function Person), then you'll be able to use it in sayName method because of closures. And that variable will not be accessible out of your "class".

Artem Sobolev
  • 5,891
  • 1
  • 22
  • 40