1

Why the second pattern is used more then the 1st when both of them do the same? Or I'm wrong?

function Foo1(){
    this.name = "Foo 1";
    this.hello = function(){
        console.log("hello", this.name);
    };
}

var test1 = new Foo1();
test1.hello();



function Foo2(){
    this.name = "Foo 2";
}

Foo2.prototype.hello = function(){
    console.log("hello", this.name);
};

var test2 = new Foo2();
test2.hello();
gskalinskii
  • 967
  • 2
  • 11
  • 17
  • First creates an anonymous function per instance, while the second creates once per prototype. – zerkms Mar 13 '14 at 23:23
  • 1
    The second allows the *hello* method to be replaced on both existing and new instances. Changing *hello* in the first example only changes the method for new instances (i.e. those created after the change). – RobG Mar 13 '14 at 23:44
  • @zerkms—the function might be "anonymous" at the point of creation, but once assigned to a variable, is it any more anonymous than if it had been created by a function declaration? ;-) – RobG Mar 13 '14 at 23:46
  • @RobG: it's not. I just commented this particular piece of code which only contains function expressions – zerkms Mar 13 '14 at 23:59
  • possible duplicate of [Javascript: prototypal inheritance](http://stackoverflow.com/questions/892595/javascript-prototypal-inheritance) – gskalinskii Mar 14 '14 at 00:17
  • As answers indicate; prototype is shared among instances. Members declared with `this.someMember` are unique for every instance while `MyConstructor.prototype.someMember` are shared by all instances either already created or to be created. It saves memory and initialization time but can also be used in inheritance patterns. More info on prototype can be found here: http://stackoverflow.com/a/16063711/1641941 – HMR Mar 14 '14 at 00:47

1 Answers1

2

Objects occupy less memory this way. There needs to be only one function in a class, as opposed to one function for each instance. This also mirrors classical inheritance.

sabof
  • 8,062
  • 4
  • 28
  • 52