Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof, scopes and objects

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.

like image 717
smoebody Avatar asked Jan 22 '26 11:01

smoebody


1 Answers

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:

  1. A factory function should not be called with new. Only constructor functions should be called with new. Furthermore even if you do call fooFactory with new it would make absolutely no difference as you're explicitly returning an object literal anyway. In fact it would be slower.
  2. 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 returns foo and not an object which has a foo property.
  3. 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 the prototype of that function and binds it to this inside the function. As long as you don't explicitly return an object from the constructor function this is returned automatically.

Hope that helps.

like image 69
Aadit M Shah Avatar answered Jan 25 '26 10:01

Aadit M Shah