开发者

Store javascript variables in array

I am sure someone has gone over this but I have had no luck finding some results. I want to know what is the fastest way to maintain a proper variable scope. Here is some example jquery code I wrote this morning.

var oSignup = {
    nTopMargin: null,
    oBody: $("div#body"),
    oSignup: $("div#newsletter_signup"),
    oSignupBtn: $("div#newsletter_signup a.btn-s4")
}

oSignup.nTopMargin = Math.abs(oSignup.oSignup.offset().top);
oSignup.oSignupBtn.toggle(function(){
    oSignup.oSignup.css({"top":0});
    oSignup.oBody.css({"top":oSignup.nTopMargin});
},function(){
    oSignup.oSignup.css({"top":-(oSignup.nTopMargin)});
    oSignup.oBody.css({"top":0});
});

Is this good or bad 开发者_运维技巧practice?


This is not "ideal". Here are the issues:

  • Don't mix/match declaration styles, if everything can be done within a {} declaration, do it that way, if it can't, be very judicious with how you choose things
  • Don't have the name of the object be the same as a field it contains. Its certainly valid, but not a "good" idea, hard to understand and maintain.


Essentially, what you're talking about is namespacing. That is, keeping your application's variables and logic separate from everything else. As long as you're aware of the pitfalls of not doing this, you're head and shoulders above most others (present company excluded).

Michael's advice is succinct and true, but you're going in the right direction. If you'd like more advice about best practices for namespacing just checkout most of the top results in a Google search, but Dustin Diaz's article in particular that will give you a dense, but very versatile way of namespacing and much more.


I'm with Zoidberg. This is just fine. In fact, it's quite a bit more elegant than quite a few other's I've seen and would rate a +1 code review from me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜