bind 方法模擬時(shí)的arguments
我有些不太理解兩個(gè) arguments 的變化,
demo:
function?foo(x,y,z){
??this.b?=?100;
??return?this.a+x+y+z;
}
var?func?=?foo.bind({a:1},20);
func(3,4);這個(gè)時(shí)候?qū)τ诮貓D右邊實(shí)現(xiàn)bind 模擬的代碼而言,
var?aArgs?=?Array.prototype.slice.call(arguments,1);??//此時(shí)的arguments[0]->{a:1}
?????????????????????????????????????????????????????//arguments[1]->20而fBound 的匿名函數(shù)中
aArgs.concat(Array.propotype.slice.call(arguments))??//此時(shí)的arguments[0]->3 ????????????????????????????????????????????????????//arguments[1]->4
我感覺這樣理解才是對(duì)的,這樣 concat 之后返回的是 [20,3,4]
但是我不太明白fBound 的匿名函數(shù)中的 arguments 是何時(shí)指向函數(shù)調(diào)用的?
2015-06-05
非常認(rèn)真的總結(jié),很不錯(cuò)。加油哦。有問題可以微博艾特我@Bosn
2015-05-19
額, 自己犯傻了??!
自問自答之前先重申一下:標(biāo)識(shí)符 arguments 是指向 【實(shí)參】 對(duì)象的引用。
也就是說,必須 【在函數(shù)調(diào)用,傳入了實(shí)參時(shí),才有 arguments 對(duì)象】。
demo:
function?foo(x,y,z){ ??this.b?=?100; ??return?this.a+x+y+z; } ? var?func?=?foo.mybind({a:1},20);??//因?yàn)?.bind()方法已存在,為了斷點(diǎn)調(diào)試,改為?.mybind()?方法 func(3,4);其中,
var?func?=?foo.mybind({a:1},20);???//?此時(shí)全部實(shí)參為?[{a:1},20]在Chrome 的控制臺(tái)下模擬了一下,注意兩點(diǎn):
此時(shí)call stack(紅色框) 里面是 第33 行調(diào)用 .mybind() 方法調(diào)用了第14行
第 20 行,也就是最后返回的函數(shù)的 arguments(藍(lán)色框) 也是[{a:1},20],但此時(shí)這個(gè)函數(shù) 【沒有調(diào)用】,沒有執(zhí)行也就沒有輸出效果。
.mybind() 返回一個(gè)函數(shù),保存在 func 里面,現(xiàn)在 func 里面是 .bind() 方法返回的函數(shù),里面的內(nèi)容也就是這一段,
當(dāng)調(diào)用 func 函數(shù),或者說是在調(diào)用 .mybind() 方法的返回值時(shí),
此時(shí)在Chrome 中斷點(diǎn),可以看到
call stack(紅色框) 中第 34 行, func(3,4) 調(diào)用的是 fBound 方法,也就是 18-19 行的代碼
此時(shí)整個(gè) Local 的 arguments(藍(lán)色框) 都是[3,4] ,即使是被調(diào)用的函數(shù)外部(即第14行)的 arguments 也是[3,4]
此時(shí)實(shí)際上是在間接調(diào)用 foo() 函數(shù),其參數(shù)分別為 oThis 和?aArgs.concat(Array.prototype.slice.call(arguments))
閉包(紫色框)中可以看到?oThis 和 aArgs 仍然存在