views:

54

answers:

3

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?

+2  A: 

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.
Michael
I think the scoping is pretty good, one thing I would note is in your function don't say oSignup.oSignup.css, refering to global variables is BAD, use this.oSignup.css instead.
Zoidberg
@Zoidberg: but `this` is `oSignup.oSignupBtn`!
just somebody
Yes I shortly realized what I had done after I posted. I have already changed that. Aside from my name spacing mistake, is this the preferred method? Scope is important to me, but speed is more important. Is the standard method of variable creation faster? IE: var foo = "bar";
Jabes88
A: 

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.

Al W
+1  A: 

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.

James van Dyke