There are two ways of creating an object in javascript:
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.
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');
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With