I was reading this page (the factories section in particular).
It mentions to avoid using the new
keyword to prevent the case of accidently forgetting it. It suggests using factories.
Page's new Example:
function Bar() {
var value = 1;
return {
method: function() {
return value;
}
}
}
Bar.prototype = {
foo: function() {}
};
new Bar();
Bar(); // These are the same.
Page's factory example:
function Foo() {
var obj = {};
obj.value = 'blub';
var private = 2;
obj.someMethod = function(value) {
this.value = value;
}
obj.getPrivate = function() {
return private;
}
return obj;
}
Factory Cons:
- It uses more memory since the created objects do not share the methods on a prototype.
- In order to inherit, the factory needs to copy all the methods from another object or put that object on the prototype of the new object.
- Dropping the prototype chain just because of a left out new keyword is contrary to the spirit of the language.
The avoiding new
to prevent issues in case you forget is understandable. But what I'm not quite grasping is that they say the factory example takes more memory since it's not using the prototype functions. So why not use something like this instead?
My Solution:
var Foo = function () {
var foo = function () {
};
foo.prototype = {
bar: function () { }
};
return new foo();
};
Question: Am I missing something that makes this not a better solution? Does my solution remove the listed cons of the factory method, why or why not?