在函数声明中调用匿名函数

时间:2019-01-21 07:19:17

标签: javascript anonymous-function invoke

尝试通过传递参数来访问匿名函数“ raining”

function weather(){
    function sunny(){
        return "Sun is shining!";
    }
    console.log(sunny());

    var raining = function(num){
        var rainThisWeek = " ";
        for (var d = 0; d < num; d++){
            rainThisWeek += "pelting ";
        }
        return rainThisWeek;
    }
}
weather(); 

3 个答案:

答案 0 :(得分:1)

您可以使用函数currying访问weather()中的匿名函数。基本上,这意味着从外部函数返回匿名函数引用,并使用期望的参数执行它。

function weather(){
    function sunny(){
        return "Sun is shining!";
    }
    console.log(sunny());

    var raining = function(num){
        var rainThisWeek = " ";
        for (var d = 0; d < num; d++){
            rainThisWeek += "pelting";
        }
        return rainThisWeek;
    }
    return raining; //you can curry the anonymous function
}
//-----------------v This will return the anonymous function reference
console.log(weather()(4)); 
//--------------------^ This will execute the returned anonymous function with the parameter 4

答案 1 :(得分:0)

您可以将回调用于此类要求。

function weather(cb){
 cb();
}

var raining = function(num){
 var rainThisWeek = " ";
 for (var d = 0; d < num; d++){
  rainThisWeek += "pelting";
 }
 return rainThisWeek;
}

function sunny(){
 return "Sun is shining!";
}

// for sunny pass sunny as callback to weather function

weather(sunny)

// for raining pass raining as callback to weather function

weather(raining.bind(null, 10))

答案 2 :(得分:0)

您定义了下雨方法的方式,您无法在函数外部访问它。您要么需要返回方法

  function weather(){
        function sunny(){
            return "Sun is shining!";
        }
        console.log(sunny());
    
        var raining = function(num){
            var rainThisWeek = " ";
            for (var d = 0; d < num; d++){
                rainThisWeek += "pelting";
            }
            return rainThisWeek;
        }
        return raining
    }
    weather()(4);
    

或在实例或原型上对其进行定义

function weather(){
        function sunny(){
            return "Sun is shining!";
        }
        console.log(sunny());
    
        this.raining = function(num){
            var rainThisWeek = " ";
            for (var d = 0; d < num; d++){
                rainThisWeek += "pelting";
            }
            return rainThisWeek;
        }
    }
    const weather1 = new weather();
    console.log(weather1.raining(3));