There are two ways of creating an object in javascript:
- use new on a “constructor function”
- 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…)?
They’re not equivalent, especially when considering prototype inheritance.
The only way you could achieve that in the fooFactory way would be to add it to the
objectprototype 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
FooTypeobject, it create a new “hello” function. If you have lots of these objects, that’s a lot of wasted memory.Consider using this instead: