简体   繁体   中英

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?

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)

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, eg:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM