Scope of JavaScript variables (XUL-related)

纵饮孤独 提交于 2019-12-06 15:14:56

You are expecting it to behave like languages you are used to with block scope. I suggest reading through Douglas Crockford's book "The Good Parts" to get a better understanding of why everything works the way it does. If you learn all of this from the start you will have a much easier time down the road.

Javascript is functionally scoped.. in this example test is scoped inside of foo.

var foo = function() {
    var test = "Peanut Butter";
};

In this example, you can see that the function can modify test as it's a globally scoped variable.

var test = "peanut butter";
var foo = function() {
    test = "Apple sauce";
};

There are three ways to define globally scoped variables, all of which I would suggest you avoid (not entirely, that's impossible). Global variables are necessary, however they can be mitigated. Their lifetime is as long as the javascript is loaded. If you define multiple global variables in different .js files that are loaded by the same page, those global variables are accessible by both, making it quite easy to accidentally overwrite vars from different files.

1: Place a var statement outside of any function, like you have done.

2: Add it as a property to the global object.

window.foo = value;

3. use a variable without declaring it, this is an implied global. Really watch out for these. The function you declared is actually an implied global itself called "clickhandler".

foo = value;

A common practice to minimize the use of global variables is known as Global Abatement, in which you define an application specific global variable to hold the rest of your global variables, to avoid collision with other libraries. This is done by declaring an object literal and using the 2nd method of creating global variables. Only use this when you need global variables however, and try to stick to functional scope when possible.

var AWESOMENEWAPP = {};
AWESOMENEWAPP.test = "Peanut Butter";

When you get deeper in to the world of javascript, you'll start learning about useful things like closures and more to keep your code clean and organized.

Just don't expect javascript to work like your typical classical languages and you'll find that it is a powerful language in its own right, just different.

On your journey, I suggest using the tool JSLint to test your code for following conventions and errors you won't see because it isn't compiled.

Yes, global functions and variables exist until the user leaves the application or closes that tab if you are using a browser. That is why it is best practice to try not to flood your global scope with variables or functions if possible.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!