How to get variables from the outside, inside a function in jQuery?
This question already has an answer here:
The reason the second example works is because you're defining myvar
as a global variable (which is accessible from anywhere).
The first example doesn't work because the variable is defined within functional scope (meaning it's inaccessible from all except that function's scope, and the scope of functions defined within that parent function's scope).
As stated in the comments, this is just how JavaScript works. If this is a problem you're running into then it's probably time to rethink your architecture.
One common pattern is to define shared variables as properties of parent objects or functions. For example:
$(function() {
var funcOne = function() {
this.sharedVal = 'stack overflow';
};
var funcTwo = function() {
console.log(funcOne.sharedVal);
};
});
This way you can have distinct functions that are able to share their properties from within other within other functions, whilst also keeping the global namespace clean. Note, however, that in this example, a simple var x = 'something';
which isn't bound as a property of another function would do just as well.
Its all about scoping, in your second example myvar is in the global scope whereas in the first its contained in the function.
You can force it to be global though:
$(function(){
window.myvar = "stackoverflow";
});
$(function(){
alert(myvar);
});
(assuming this is in the browser)
The is due to scope of variable. Variable defined in $(function() has scope inside the this function. The enclusre here descide the scope. The variable defined outside function have global scope and defined in window object.
Scope inside function.
$(function(){
var myvar = "stackoverflow";
});
// myvar is not accessible here.
Scope inside window object.
$(function(){
window.myvar = "stackoverflow";
});
// myvar is accessible here.
链接地址: http://www.djcxy.com/p/40818.html
上一篇: 我什么时候使用var?