我遇到了一些代码对我来说看起来很混乱,虽然我在很多地方搜索谷歌搜索,我找不到我的问题的确切答案。希望知道这个代码发生了什么,我在这里,问我是否有一个很好的解释,所以我不仅知道该怎么做,而且还要了解它的作用!
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"?
答案 0 :(得分: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();