开发者

Single instance of a class in javascript

Javascript allows defining a function as

function Name() { content; }

and

var Name = function() { content; }

开发者_如何转开发Is there an equivalent for classes? I'm looking to create a single instance of a class. The only way I know how to do that is

function ClassName() { content};
var instance = new ClassName();

Can I not combine those two into a single statement?

Thanks!


You don't have to use a function at all to create the object, if you just want a singleton:

var instance = {
    name: "foo",
    method: function() {
        // do something
    }
};

That creates an object with name and method properties. You don't have to add them via initialization like that if you don't want to, you can do this:

var instance = {};
instance.name = "foo";
instance.method = function() {
    // do something
};

I usually use a function when defining either a singleton or a "class" (really, a constructor function), but that's because I have a thing about named functions (the function above that I assign to the method property is anonymous, which means my tools can't help me much — with call stacks, etc.). So I would probably do this:

var instance = (function() {
    var publicSymbols = {};

    publicSymbols.name = "foo";

    publicSymbols.method = instance_method;
    function instance_method() {
        // do something
    }

    return publicSymbols;
})();

...although I usually use a shorter name for publicSymbols (wanted to be fairly clear what it did). For one thing, that lets me have truly private functions that the singleton or "class" can use that no one else can see. More here. But that's a style choice; it can be as simple as the first two examples above.


you can use this. it is a self executing function that will assign the results of the function instead.

var instance = (function className() { return something; } )();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜