1

Possible Duplicate:
Advantages of using prototype, vs defining methods straight in the constructor?

Why use:

Person.prototype.toString = function() { return this.name; }

over

Function Person(name) { 
    this.name = name;
    this.toString = function() { 
        return this.name;
    } 
}
Community
  • 1
  • 1
Andre
  • 1,481
  • 1
  • 17
  • 38

3 Answers3

4

Well, you should use prototypes because of code reuse and inheritance.
Basically, if you bind a method to the this keyword, you are providing that method to only that particular instance, while with prototype, you write the method for all instances of that class.
ex:

function Person(name) {
    this.name = name;
    this.toString = function() {
        return this.name;
    }
}
var bob = new Person('Bob');
var jim = new Person('Jim');
jim.toString = function() {
    return "I have amnesia, I forgot my name!";
};

Now, although bob and jim are both persons (instances of the same class), they behave differently, because they have their own set of rules (methods) that they rely on.
If you were to use a prototype:

function Person(name) {
   this.setName(name);
}
Person.prototype = {
    name : 'default name',
    setName : function(name) {
        this.name = name;
    },
    toString : function() {
       return this.name;
    }
};
var bob = new Person('Bob');
var jim = new Person('Jim');
Person.prototype.toString = function() {
    return "I have amnesia, I forgot my name!";
};

Now, all of your persons behave the same.
Using prototypal inheritance is benefic for code reuse and it won't load the memory with unnecessary duplicate things. + Updating classes is muuuch more easy this way.

gion_13
  • 39,371
  • 9
  • 93
  • 105
2

One reason is because it will update/add that function to objects of that type that have already been created.

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

var person = new Person("Test");
alert(person.toString()); // alerts [object Object]

Person.prototype.toString = function() {
    return this.name;
};
alert(person.toString()); // alerts Test

http://jsfiddle.net/28puy/

Richard Dalton
  • 34,315
  • 6
  • 69
  • 88
1

In javascript, methods are objects. In your second Person constructor, you're creating a new instance of the toString function for each instance of Person. By using the prototype object, there is just one instance of the toString function that will be shared among all instances of Person.

cbare
  • 10,730
  • 6
  • 47
  • 57