簡體   English   中英

返回帶有參數的函數的JavaScript函數

[英]JavaScript function that returns function with parameters

我正在nodeschool-homepage上進行函數式編程的教程。 我是JS的新手(來自Java),所以我不了解JS的某些方面,例如:

function say(word) {
   return function(anotherWord) {
        console.log(anotherWord);
    }
}

如果我打電話給:

say("hi"); // it returns nothing

say("hi", "hi"); // it returns nothing

var said = say("hi"); // asignment

said("hi"); // returns hi -- but why?

said(); // returns undefined;

有人可以向我解釋外部函數中的“ hi”如何在內部函數中傳遞嗎?

 said("hi"); // returns hi -- but why? 

因為內部函數定義為

function(anotherWord) {
    console.log(anotherWord);
}

這意味着它將記錄傳遞的第一個參數。 您正在傳遞'hi' ,因此它記錄為'hi'

t .. f ...外部函數中的“ hi”如何在內部函數中傳遞?

不是。 內部函數僅訪問其自己的參數。 將什么作為參數傳遞給第一個函數都沒有關系。 say()('hi')say('foo')('hi')都是等效的。 重要的是傳遞給第二個函數的參數。

如果相反,您將函數定義為

function say(word) {
   return function(anotherWord) {
        console.log(word, anotherWord);
    }
}

現在,內部函數還訪問外部函數的第一個參數,因此您將獲得不同的結果。

為什么這樣做? 由於JS中的所有函數都是閉包 ,因此它們可以訪問更高范圍的變量綁定。

函數say返回一個帶有參數的函數並將其記錄下來。 傳遞給say函數的參數(參數word )將被丟棄。

您的代碼實例似乎正常工作如下:

var said = say("hi");
said("hi");

當您在此處的第一行中調用say函數時,傳入的單詞“ hi”沒有任何作用。 該函數返回另一個匿名函數,該函數存儲在said變量中。

當您在said變量中調用該函數並傳遞“ hi”時,它將按預期運行。 如果第一行是

var said = say("elephant");

函數say使用一個在任何地方都不使用的參數word ,因此沒有任何內容從“外部”函數傳遞到“內部”函數。

function say(word) {
    return function(anotherWord) {
        console.log(anotherWord);
    };
}

發生的是, say()返回一個函數。 此返回的函數采用一個參數( anotherWord ),該參數在調用時輸出到控制台。

現在到您的代碼示例:

say("hi"); // this returns a function, but you don't keep it anywhere

say("hi", "hi"); // still returns a function, still no variable to keep it

var said = say("hi"); // finally the returned function is saved, the param is not used

said("hi"); // this prints "hi", because you pass it 'hi'

said("foobar"); // this prints "foobar", because you pass it 'foobar'

said(); // This prints undefined, as you did not pass any parameter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM