开发者

Structural programming - What is this javascript pattern called? Is it okay using it?

var contextMenu = {

    isVisi开发者_StackOverflow社区ble : false,

    open : function()
    {
            //some code here
    },

    close : function()
    {
            //some code here
    }   
}

I'm using this pattern heavily in my code. My application can be done using structural programming without need for classes/object instantiation.

First I used to write something like this:

var isContextMenuVisible : false,

function openContextMenu()
{
    //some code here
} 

function closeContextMenu()
{
    //some code here
}   

Is this okay? What is this pattern called? What are the disadvantages?

EDIT: This is called as Singleton pattern

Btw, is it okay to use capitalized names for the object? Like ContextMenu instead of contextMenu? Would that be a proper convention?


Singleton is a design pattern that forces the classes that implement it to offer only one point of access to them. Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript


It is okay to using that pattern, from what you were writing before, I would say that you were scoping. The advantages is your not creating global variables, which is always a good thing. The disadvantages is that you cannot access any of the values of the object until the entire object is created ( I get caught by this a lot ).

I am not sure this pattern has a name, but I suppose, it's object literal creation.


If you dont want to use classes|object instantiation, then best way is (from your samples):

function openContextMenu() {
  // some code here
  // you can use 'this' to point to current object
} 
function closeContextMenu() {
  // some code here
  // you can use 'this' to point to current object
}  
var contextMenu = {
    isVisible : false,
    open : openContextMenu,
    close : closeContextMenu   
};
var contextMenu2 = {
    isVisible : false,
    open : openContextMenu,
    close : closeContextMenu   
};

This allow you to create more than one object, and minimize memory usage.


But next is more ease:

function ConextMenu() {
}
ConextMenu.prototype.isVisible=false;
ConextMenu.prototype.open=function openContextMenu() {};
ConextMenu.prototype.close=function closeContextMenu() {};

var contextMenu = new ConextMenu;
var contextMenu2 = new ConextMenu; // or new ContextMenu()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜