user2071276
user2071276

Reputation: 113

Can you name an instance the same as its constructor name?

Can you name an instance the same as its constructor name?

var myFunc = new function myFunc(){};

?

As it seems, this replaces the Function Object with the new instance... which means this is a good Singleton.

I haven't seen anyone using this, so I guess, there are downsides to this that I am unaware of...

Any thoughts?

Upvotes: 5

Views: 120

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92314

YES...

However, it does look weird that you're creating a named function but never refer to it by name.

The more common pattern(s) I've seen are

function MyClass(){
    this.val = 5;
};
MyClass.prototype.getValue = function() {
    return this.val;
}
MyClass = new MyClass();

But when people do that I wonder why they don't just use a literal object

var MyClass = {
    val: 5,
    getValue: function() {
        return this.val;
    }
}

And I would even prefer to use the module pattern here

var MyClass = (function(){
    var val = 5;
    return {
        getValue: function() {
            return val;
        }
    };     
})();

Disclaimer

Now whether the singleton pattern should be used, that's another question (to which the answer is NO if you care about testing, dependency management, maintainability, readability)

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816920

As it seems, this replaces the Function Object with the new instance

No, it does not replace anything. The name of a function expression (that's what you have) is only accessible inside the function itself, not outside of it. It would be exactly the same as if you omit the name:

 var myFunc = new function(){};

In general, if you don't want certain symbols accessible, just don't make them global. Define those symbols inside a function and just return whatever you want to make accessible, e.g:

var myobj = (function() {
    function Foo() {};
    // do whatever
    return new Foo();
}());

However, if you just want to create a single object, it is often easier to use an object literal:

var myobj = {};

There is no reason to use a constructor function if you only want to create a single instance from it. If you want to establish inheritance, you can use Object.create [MDN]

Upvotes: 0

Related Questions