Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
user2071276 Avatar asked Nov 12 '22 07:11

user2071276


1 Answers

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)

  • http://accu.org/index.php/journals/337
  • Why implementing a Singleton pattern in Java code is (sometimes) considered an anti-pattern in Java world?
like image 130
Juan Mendes Avatar answered Nov 15 '22 10:11

Juan Mendes