【问题标题】:Local variable inside a method, and assigning a function?方法内的局部变量,并分配一个函数?
【发布时间】:2016-01-25 01:56:03
【问题描述】:

我遇到了一些对我来说看起来很混乱的代码,尽管我在很多地方都用谷歌搜索过,但我找不到我的问题的确切答案。希望知道这段代码是怎么回事,我在这里询问是否有一个很好的解释,所以我不仅会知道如何去做,而且还要了解它的作用!

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()function(before the dot) return f 之前带有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"?

【问题讨论】:

    标签: javascript variables object return


    【解决方案1】:
    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-09
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 2022-08-02
      • 1970-01-01
      相关资源
      最近更新 更多