Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating objects with new vs. {} in javascript

Tags:

javascript

There are two ways of creating an object in javascript:

  1. use new on a "constructor function"
  2. return a dictionary {} and set the proper key/value pairs

The first is, for example

FooType = function() {
    this.hello = function() { alert("hello"); };
};

foo = new FooType();
foo.hello();

the second is

fooFactory = function() {
    return { 
        hello : function() { alert("hello"); }
    };
};

foo = fooFactory();
foo.hello();

(Code written for the post. not guaranteed correct)

Apart from risks of mistakes of having this bound to the global object, are these two method totally equivalent (also considering prototype inheritance etc...)?

like image 390
Stefano Borini Avatar asked Feb 28 '23 20:02

Stefano Borini


1 Answers

They're not equivalent, especially when considering prototype inheritance.

FooType = function() {
    this.hello = function() { alert("hello"); };
};

var foo = new FooType();

FooType.prototype.bye = function() { alert('bye!'); };

foo.bye(); // "bye!"

The only way you could achieve that in the fooFactory way would be to add it to the object prototype which is a Very Bad Idea.

The first method is much more meaningful in my opinion (since the object has a type you can check against) and can offer much better performance if the prototype is done properly. In your first example, every time you instantiate a new FooType object, it create a new "hello" function. If you have lots of these objects, that's a lot of wasted memory.

Consider using this instead:

function FooType() { }
FooType.prototype.hello = function() {
    alert('Hello');
};
like image 59
nickf Avatar answered Mar 02 '23 09:03

nickf