开发者

Is it bad practice to assign a global shortcut variable to a global namespace (object literal)?

开发者 https://www.devze.com 2023-03-06 04:16 出处:网络
I have a little quandary over whether it is good practice to do the following. I have a global object literal or namespace that I use to contain base functions and variables.

I have a little quandary over whether it is good practice to do the following.

I have a global object literal or namespace that I use to contain base functions and variables.

Within this I have a Page property which contains all the variables and functions for a specific page. I also contain re开发者_运维技巧ferences to element IDs in a property within the Page property. This is due to having an ASP.NET site whereby I need to store the .NET-generated client IDs so I can reference them with jQuery.

Base
    Base.Page
        Base.Page.Elements

My issue is that I find myself assigning "shortcut" variables to these literals within my page functions such as the following:

Base.Page.DoThisStuff = function () {
    var p = Base.Page;
    var pe = Base.Page.Elements;

    //Function Stuff Here

    p = null;
    pe = null;
}

My question is: Is it a better idea to create a 'global' variable in my master page, such as var _p = Base.Page; or is this horrible and bad practice and I should continue as above?

(My namespaces don't have names as short as the above - they are just for illustration.

I have not tagged ASP.NET or jQuery as I don't think they directly relate to this question.)


This really seems to me a question of programming style, and each answer will vary.

I would keep my variables in as smaller a scope as possible, hence, I would prefer the solution above rather then the global variables shortcuts idea.


In general you'll want to limit your global "footprint", mainly to avoid another piece of js redefining some of your globals. I would say that the simpler the identifier is, the most likely it is that someone else might use it.

What I've seen in extjs and I think is a good compromise is that they'll define shorthands just under the Ext namespace. For example get a component you'll have the Ext.getCmp method which,if I recall correctly, is a shortcut to Ext.ComponentMgr.get.

So you'd keep Base.Page, and maybe Base.pe if you very often need access to page elements.

0

精彩评论

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