could anyone explain this behaviour to me, please?
'use strict'
var fooFactory = function() {
function foo() {
var name = "foo object";
function getName() {
return name;
}
return {
getName: getName
}
}
function getFoo() {
return new foo;
}
return {
getFoo: getFoo,
foo: foo
}
};
var factory = new fooFactory();
var bar = factory.getFoo();
console.log("is " + bar.getName() + " instance of foo: " + (bar instanceof factory.foo));
// outputs "is foo object instance of foo: false"
i don't understand, why the foo object is no instance of the foo constructor i declare inside the fooFactory.
You're explicitly returning an object from the
foofunction. That object is not an instance offoo. Hencebaris not an instance offoo. This is how I would rewrite your code:The reason I would write it like this is as follows:
new. Only constructor functions should be called withnew. Furthermore even if you do callfooFactorywithnewit would make absolutely no difference as you're explicitly returning an object literal anyway. In fact it would be slower.fooFactoryI would assume that it returnsfooand not an object which has afooproperty.newJavaScript automatically creates a new instance of theprototypeof that function and binds it tothisinside the function. As long as you don't explicitly return an object from the constructor functionthisis returned automatically.Hope that helps.