Reputation: 143785
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...)?
Upvotes: 4
Views: 311
Reputation: 546025
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');
};
Upvotes: 6
Reputation: 35830
In example one, foo
inherits from FooType
's prototype (which hasn't had any changes). foo instanceof FooType
is true in the example. In example two, there's no inheritance. If you are going to be reusing methods, use example one but define shared methods on FooType.prototype
, not in the function body:
var FooType = function() {};
FooType.prototype.hello = function() { alert("hello"); };
Upvotes: 2