admin 管理员组

文章数量: 1087649

On executing

var a=b=c=d=e=f=a; 
//no error(a has not initialize before)

var x=y;
//ReferenceError: y is not defined

How can the first code just execute as if a has already been initialize before.

On executing

var a=b=c=d=e=f=a; 
//no error(a has not initialize before)

var x=y;
//ReferenceError: y is not defined

How can the first code just execute as if a has already been initialize before.

Share Improve this question asked Jul 8, 2013 at 7:00 vusanvusan 5,3314 gold badges48 silver badges83 bronze badges 2
  • 5 first statement is like var a = undefined; window.b=window.c=window.d=window.e=window.f=a; in second y is not defined – rab Commented Jul 8, 2013 at 7:03
  • 1 @rab just post that as an answer. It's the correct one – rossipedia Commented Jul 8, 2013 at 7:04
Add a ment  | 

2 Answers 2

Reset to default 11

It's because of variable hoisting. var x = EXPR; is actually converted to this:

// beginning of the block (function/file)
var x; // === undefined
// ...
// the actual position of the statement
x = EXPR

For your example this means:

var a;  // === undefined
a = b = c = d = e = f = a;

Note that only a is declared using var - so you are creating tons of globals which is always a bad thing!

Your first statement is like

var a = undefined; 
a = window.b = window.c = window.d  = window.e = window.f = a; 

where a is defined, and others are global scoped . suppose you execute a function .

(function(){
  var a=b=c=d=e=f=a; 
  b = 10;
}());

the b can accessed outside .

in second var x=y , y is not defined yet

本文标签: javascriptAssigning the variable name to the same variable nameStack Overflow