最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

oop - Single instance of a class in javascript - Stack Overflow

programmeradmin1浏览0评论

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 bine those two into a single statement?

Thanks!

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 bine those two into a single statement?

Thanks!

Share Improve this question asked Jan 5, 2011 at 14:18 MikhailMikhail 9,0079 gold badges57 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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)

  1. 暂无评论