You're explicitly returning an object from the foo
function. That object is not an instance of foo
. Hence bar
is not an instance of foo
. This is how I would rewrite your code:
var foo = fooFactory();
var bar = new foo;
console.log("is " + bar.getName() + " instance of foo: " +
bar instanceof factory.foo);
function fooFactory() {
return function () {
var name = "foo object";
this.getName = function () {
return name;
};
};
}
The reason I would write it like this is as follows:
- A factory function should not be called with
new
. Only constructor functions should be called withnew
. Furthermore even if you do callfooFactory
withnew
it would make absolutely no difference as you're explicitly returning an object literal anyway. In fact it would be slower. - Instead of returning an object with the constructor function and another function which instantiates the constructor wouldn't it be better to simply return the newly created constructor itself? Since your factory is named
fooFactory
I would assume that it returnsfoo
and not an object which has afoo
property. - If you're going to create a function and use it as a constructor then don't explicitly return an object from it. When you call a function using
new
JavaScript automatically creates a new instance of theprototype
of that function and binds it tothis
inside the function. As long as you don't explicitly return an object from the constructor functionthis
is returned automatically.
Hope that helps.