How to use a return value in another function in Javascript?

前端 未结 6 891
傲寒
傲寒 2020-12-03 02:02

I\'m self-teaching myself JavaScript and out of curiosity I\'m wondering what is the proper way of returning a value from one function to be used in another function. For ex

6条回答
  •  天涯浪人
    2020-12-03 02:27

    You could call firstFunction from secondFunction :

    function secondFunction() {
        alert(firstFunction());
    }
    

    Or use a global variable to host the result of firstFunction :

    var v = firstFunction();
    function secondFunction() { alert(v); }
    

    Or pass the result of firstFunction as a parameter to secondFunction :

    function secondFunction(v) { alert(v); }
    secondFunction(firstFunction());
    

    Or pass firstFunction as a parameter to secondFunction :

    function secondFunction(fn) { alert(fn()); }
    secondFunction(firstFunction);
    

    Here is a demo : http://jsfiddle.net/wared/RK6X7/.

提交回复
热议问题