What’s the purpose of prototype?

javascript, prototype-programming

Solution

Using the prototype makes faster object creation since properties/methods on the prototype don't have to be re-created each time a new object is created.

When you do this:

function animal() {
    this.name = 'rover'
    this.set_name = function (name) {
      this.name = name
    }
}

The `set_name` method is created every time you create an animal. But when you do this

animal.prototype.set_name = function (name) {
    this.name = name
}

The method does not have to be re-created each time; it exists in one place in the prototype. So when you call `someAnimal.set_name("Ubu");` the `this` context will be set to `someAnimal` and (the one and only) `set_name` method will be called.

There is one advantage to using the first syntax though: methods created in this manner will have access to private data:

function animal() {
    var privateData = 'foo'

    this.name = 'rover'
    this.set_name = function (name) {
        this.name = name
        alert(privateData) //will alert 'foo'
    }
}

Douglas Crockford calls methods created like this "privileged" for that reason: they have access to both public and private data.

Problem

Possible Duplicate: Use of 'prototype' vs. 'this' in JavaScript? OK, So I am somewhat new to the idea of OOP in JS. What is the difference between these two snippets of code written below: ``` function animal(){ this.name = 'rover'; this.set_name = function(name){ this.name = name; } } ``` ``` function animal(){ this.name = 'rover'; } animal.prototype.set_name = function(name){ this.name = name; } ``` They both do the same thing, so what’s the difference?

Original source

Related problems