2015-10-26 44 views
0

我遇到了一些代碼,對我來說看起來很混亂,雖然我在很多地方搜索了一遍,但我找不到我的問題的確切答案。希望知道這段代碼發生了什麼,我在這裏,問我是否有一個很好的解釋,所以我不僅知道該怎麼做,而且還要學習它的功能。方法內的局部變量,並分配一個函數?

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() < =這些括號會讓我困惑,因爲如果fa_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"? 

回答

0
var anonymous = function(){var f = function(){alert()}; return f}();anonymous(); 
var anonimo = {method:function(){var f = function(){alert("this is an anonimous function")}; return f;}()} 
anonimo.method(); 
var why = {method:function(){ 
var f = function(){ 
alert("this an anonymous function because the function was declared from a variable, is this right?") 
}; 
f.notHere = function(){ 
alert("correct me if I'm wrong but, f is variable declared to an anonymous function just f alone \"notHere\"") 
}; 
return f 
}()}; 
why.method.notHere(); 
var lastScenario = { 
method:function(){ 
var f = function(){}; 
f.notHere=function(){ 
alert("this will not work if I don't declare f as a function") 
};return f}()}; 
lastScenario.method.notHere(); 
相關問題