thandasoru
thandasoru

Reputation: 1558

What is the advantage of using Prototype in Javascript?

I read crockford's page on private members http://javascript.crockford.com/private.html in Javascript and got a question which maybe somewhat related. Why should a developer use Prototype?

For example,

For example, I can do this

var Foo = new Object();
Foo.bar = function() { alert('Its a bar'); };
var x = Foo;
x.bar();

instead of

var Foo = function(){};
Foo.prototype.bar = function(){alert('Its a bar');};
var x = new Foo();
x.bar();

Both of these implementations do the same thing. How is one different from the other? Does this affect inheritance in any way?

Upvotes: 2

Views: 1818

Answers (1)

Matt
Matt

Reputation: 75317

When you use the prototype pattern, only one instance of attributes you add to the prototype exist.

// Lets create 1000 functions which do the same thing
for (var i=0;i<1000;i++) {
    Foo = new Object();
    Foo.bar = function() { alert('Its a bar'); };

    var x = Foo;
    x.bar();
}

// This is the same as #1, but is more common
function Foo() {
    this.bar = function () { alert('It\'s a bar'); };
}
for (var i=0;i<1000;i++) {
    var x = new Foo;
    x.bar();
}

// Lets create 1 function
var Foo = function(){};
Foo.prototype.bar = function(){alert('Its a bar');};
for (var i=0;i<1000;i++) {
    var x = new Foo();
    x.bar();
}

The prototype pattern has the disadvantage of not being able to access private members.

// Lets create 1 function
var Foo = function(){
    var private = 4;

    this.baz = function () {
        alert(private);
    }
};
Foo.prototype.bar = function(){alert(private);};

var x = new foo;
x.bar(); // error; `private` is undefined
x.baz(); // ok

Upvotes: 3

Related Questions