JavaScript scope chain

  • 1367
  • 0
  • 2011-10-24

摘要:JavaScript, scope chain

JavaScript fun

function wl(s){document.write((s||'')+"<br />\r\n");}

function test1() {
	return say();
	function say() {
		return 't';
	}
}
wl('1:'+test1());//t

var t2 = 20;
function test2() {
	return say();
	var t2 = 10;
	function say() {
		return t2;
	}
}
wl('2:'+test2());//undefined
/*
undefined?我以為是 20....囧a
return 後面不執行,裡面找不到 t2,那應該會去找外面吧…
*/

var t2_1 = 20;
function test2_1() {
	return say();
	function say() {
		return t2_1;
	}
}
wl('2_1:'+test2_1());//20
/*
所以....宣告不管寫在哪都會被拉到前面?
function test2() {
	return say();
	var t2 = 10;
	function say() {
		return t2;
	}
}
被解釋成這樣? ↓
function test2() {
	var t2;
	return say();
	t2 = 10;
	function say() {
		return t2;
	}
}
*/

var t3 = 20;
function test3() {
	return say();
	var t3 = 10;
	function say() {
		return this.t3;
	}
}
wl('3:'+test3());//20, this=window

var t4 = 20;
function test4() {
	var t4 = 10;
	return say();	
	function say() {
		return t4;
	}
}
wl('4:'+test4());//10, closure


var t5 = 20;
function test5() {
	var t5 = 10;
	return say();	
	function say() {
		return this.t5;
	}
}
wl('5:'+test5());//20


var t6 = 20;
function test6() {
	this.t6 = 10;
	function say() {
		return this.t6;
	}
	this.g=say;
	return say();
}
var obj=new test6();
wl('6 new:'+obj.g());//10
wl('t6:'+t6);//20
wl('6 :'+test6());//10 沒加 new會動到全域(window)變數
wl('t6:'+t6);//10
wl('6 new:'+obj.g());//10

 

more:Javascript面面觀:核心篇《變數範圍》