Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Is there a difference between this.foo and this.prototype.foo [duplicate]

Is there any difference between this:

function Foo(){
    this.bar = function(){
        console.log('hello');
    }
}
fooObj = new Foo();

and this?

function Foo(){

}

Foo.prototype.bar = function(){
    console.log('hello');
}
fooObj = new Foo();

These seem to behave the same, but I don't yet have a full understanding of prototypes. Is foo.prototype just a way of declaring a method outside of a class?

like image 692
starscape Avatar asked Jan 24 '26 21:01

starscape


1 Answers

The first example creates a new function object for each new object created with that constructor and assigns it to the property, the second example creates a single function that each new object references.

This means that for instance for your first example

var fooObj1 = new Foo();
var fooObj2 = new Foo();

alert(fooObj1.bar === fooObj2.bar) //false

while for the second

alert(fooObj1.bar === fooObj2.bar) //true

This is because in the first example the bar properties refer to 2 seperate but identical objects, while for the second they are the same.

In general the recommendation is that functions should be declared on the prototype to preserve memory, while other objects should be declared individually, unless you want to declare a "static" object that is shared among all objects created with that constructor.

Its easier to see the distinctions with normal objects or arrays rather than functions

function Foo(){
    this.bar = [];
}
var fooObj1 = new Foo();
var fooObj2 = new Foo();

fooObj1.bar.push("x");
alert(fooObj2.bar) //[]

as opposed to:

function Foo(){
}

Foo.prototype.bar = []
var fooObj1 = new Foo();
var fooObj2 = new Foo();

fooObj1.bar.push("x");
alert(fooObj2.bar) //["x"]
like image 166
Ben McCormick Avatar answered Jan 27 '26 12:01

Ben McCormick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!