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

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

var myFunc = new function myFunc(){};

?

This seems to replace the Function object with a new instance ... which means it's a good singleton.

I have not seen anyone use this, so I think there are downsides to this that I don't know about ...

Any thoughts?

+5
source share
2 answers

YES...

However, it is strange that you create a named function, but you never reference it by name.

The more common patterns I've seen

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

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

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

And I would even rather use the module template here

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

Renouncement

, singleton, ( , , , , )

+1

, Function

, . (, ) , . , :

 var myFunc = new function(){};

, , , . , , :

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

, , :

var myobj = {};

, . , Object.create [MDN]

0

All Articles