Javascript scope
I have a script with a similar structure to this
$(function(){
var someVariable;
function doSomething(){
//here
}
$('#something').click(function(){
//here
})
});
My question is;
From the doSomething function, and the click handler开发者_开发技巧
how can I access the someVariable without passing it in?Just use it. No need for this
.
$(function(){
var someVariable = 3;
function doSomething(){
alert(someVariable);
}
});
You can use it without any special syntax. someVariable
is available in closure scope of doSomething
.
Read more on JavaScript closures
When ECMA- / Javascript
methods are invoked (called), several things happen. To make a long story short, when a function is called a such called Activation object is created for that function. In that object you'll find things like arguments, local variables and function declarations and the arguments object. The "Context" of the invoked function has a [[Scope]]
property. That is the place where all parent context's are stored when the function is invoked.
That concept (which I pretty much shrinked together here) is the basic thing to have closures. That means if you call doSomething()
in your example, the function will copy the parent Context into it's [[Scope]]
, which includes someVariable
. The anonymous function from your event listener does the same thing, both methods share the same scope.
Short answer: You can just use and access someVariable
in all of methods.
精彩评论