I do not understand this behavior:
var a = 1;
console.log('a is undefined1:', a == undefined);
var a;
//iterate selected jQuery elements:
jQuery.e开发者_运维知识库ach(this, function(index, htmlElement) {
console.log('a is undefined2:', a == undefined);
var a;
Returns:
a is undefined1: false a is undefined2: trueIf the last line (var a;) is commented out, this is returned:
a is undefined1: false a is undefined2: falseI would expect always the latter output. What do I not know?
Thanks so much!
Putting var a
inside a function creates a different a
variable that is scoped to that function.
Since you don't assign a value to it, it is undefined.
When you comment it out, you are testing the outer a
which has the value of 1.
Variables are hoisted. It doesn't matter where in a function you use var foo
, the foo
for that function still applies to the whole function.
Declaring variable within function using var
makes local copy (new variable) with scope on the whole function - it does not matter whether it is used before it is declared.
Never declare variables without var
.
If you want to access the golobal variable and you have local variable of the same name, you can access the global foo
variable using window.foo
精彩评论