Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Why a variable defined global is undefined?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have just stumbled on a js "feature" called hoisting

var myname = "global"; // global variable
function func() {
    alert(myname); // "undefined"
    var myname = "local";
    alert(myname); // "local"
}
func();

In this code when you define func the compiler looks at the function body. It sees that you are declaring a variable called myname.

Javascript Hoists variable and function declarations, by moving the declaration to the top of the function.

Because of hoisting your code is rewritten to the following.

var myname = "global"; // global variable
function func() {
   var myname; //declare local variable and assign it undefined
   alert(myname); // "undefined"
   myname = "local"; // assign local var myname to "local"
   alert(myname); // "local"
}
func();

This "Covers" the global variable. If you want access to the global variable within the scope of a function use the this keyword.

var myname = "global"; // global variable
function func() {
    var myname = "local";
    alert(this.myname); // "global"
    alert(myname); // "local"
}
func();

Note that this only works in calling a function not a method or constructor because the this keyword changes what its bound to based on how you call a function.

EDIT: For completeness

If you want to get access to global variables in any context regardless of function type then declare a global variable that by convention you never cover.

var global = this; // in global scope.
var myname = "global";
var obj = {f: function () {
    var myname = "local";
    console.log(global.myname);
}};
obj.f(); // "global"

Note that this is in method position and the this keyword refers to obj directly and therefore doesn't have myname defined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...