我遇到了一些代碼,對我來說看起來很混亂,雖然我在很多地方搜索了一遍,但我找不到我的問題的確切答案。希望知道這段代碼發生了什麼,我在這裏,問我是否有一個很好的解釋,所以我不僅知道該怎麼做,而且還要學習它的功能。方法內的局部變量,並分配一個函數?
var fun = {
a_method: function(){
var f = function(){
alert("FUN FUNNY FUNCTION");
};
f.another_method = function(){ // in this line, is another_method local or not? Because like mentioned f is local; how about another_method after the dot?
alert("this is another method inside my fun method");
};
return f; // this is a local variable, why another_method isn't local?
}() // these parentheses, what do they do in regards to the function?
};
return f
是做什麼用的?爲什麼f.another_method(){function(){}}
變成fun.a_method.another_method()
< =這些括號會讓我困惑,因爲如果f
在a_method
之內,那麼同樣不應該是所有其他地方都是本地的嗎?像f.another_method(){function(){...}}
,或者甚至更清晰我想知道爲什麼.another_method()
與f
之前function(before the dot) return f
。並傳遞給another_method()
?在fun.a_method.another_method();
和f
這裏可以看到混淆的地方。
fun.a_method.another_method()
< =這些括號迷惑我 f.another_method(){function(){}};
我應該這樣調用它,但我不正確的(爲什麼,只因爲變量是本地的),這是不是它如何與JS的工作原理:
fun.a_method.f.another_method();
試圖瞭解爲什麼不上面,而不是:
fun.a_method.another_method(); // note that it is without the "f" when it's called, now why not or "how it became this way"?