Creating objects with the new vs. {} in javascript

There are two ways to create an object in javascript:

  • use the new constructor function
  • return the dictionary {} and set the corresponding key / value pairs.

First of all, for example,

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

second

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

(Code written for the message is not guaranteed)

Besides the risks of errors associated with this related global object, are these two methods completely equivalent (also considering prototype inheritance, etc.)?

+4
source share
2 answers

They are 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 this in fooFactory is to add it to the object prototype, which is a very bad idea.

The first method is much more significant, in my opinion (since the object has a type that you can check) and can offer much better performance if the prototype is executed correctly. In the first example, every time you create a new FooType object, it creates a new hello function. If you have a lot of such objects, this is a lot of lost memory.

Consider instead:

 function FooType() { } FooType.prototype.hello = function() { alert('Hello'); }; 
+6
source

In example one, foo inherits the prototype FooType (which did not have any changes). foo instanceof FooType true in the example. In example two, there is no inheritance. If you intend to use reuse methods, use example one, but define common methods on FooType.prototype , and not in the function body:

 var FooType = function() {}; FooType.prototype.hello = function() { alert("hello"); }; 
+2
source

All Articles