0

How to correctly define a method for an object in JavaScript? The MDN shows example with prototype:

var Person = function (firstName) {
    this.firstName = firstName;
};

Person.prototype.sayHello = function() {
    console.log("Hello, I'm " + this.firstName);
};

var person1 = new Person("Alice");

// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"

But why I need to add methods outside the constructor if I can add it inside of it using this:

var Person = function (firstName) {
    this.firstName = firstName;

    this.sayHello = function() {
        console.log("Hello, I'm " + this.firstName);
    };
};

var person1 = new Person("Alice");

// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"

Are there any reasons to define method via prototype? And what the difference between these two approaches?

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
  • 1
    Prototypes allow more effective object creation because prototype methods are shared and not recreated like in case of methods defined as own properties inside of constructor. So if you plan to have multiple instances of the Person then you should use prototype-way. – dfsq Dec 25 '15 at 11:05
  • 1
    Checkout answer to [this](http://stackoverflow.com/questions/310870/use-of-prototype-vs-this-in-javascript) questions it will cover your question too. – Andriy Ivaneyko Dec 25 '15 at 11:06
  • @dfsq It makes sense! Thank you! – Victor Bocharsky Dec 25 '15 at 11:08
  • i am new in computer science.. if u r using jquery.. then maybe protoype can be call like this $.fn.methodname =function(){} – Phoenix Dec 25 '15 at 11:10
  • Thanks to all, guys! – Victor Bocharsky Dec 25 '15 at 11:12

0 Answers0