簡體   English   中英

JavaScript函數中的相鄰括號是如何工作的,在哪里記錄?

[英]How do adjacent parentheses in JavaScript functions work, and where is this documented?

在將其標記為重復項之前,請注意:我理解IIFE是什么。 這個問題與IIFE無關。

問題:即使在標准函數調用中,JavaScript為什么也能夠解析相鄰的括號? 這種構造myFunction()() -如何工作? 例如,這是使用Jasmine進行測試的一些代碼:

var element = compile('<div my-directive></div>')(scope);

為什么我們要走這條路線而不是將范圍作為第二個參數? 我認為這與保持全球環境整潔沒有任何關系,除了關於IIFE的地方,我在任何地方都找不到關於這種特殊構造的東西。 這個結構有名稱嗎?

最重要的是,請提供某種權威參考(鏈接到mdn,ecmascript規范等)。

這是兩個規則的結果:

  1. 函數調用的返回值可以立即使用(無需分配給變量)。

  2. 函數是對象(它們可以分配給變量,可以作為參數傳遞並從函數調用中返回)。

第一條規則意味着,如果您有執行此操作的代碼:

function a () { return { hello : 'world' } }

你可以這樣做:

a().hello; // returns 'world';

基本上與不使用任何臨時變量的情況相同:

var tmp = a();
tmp.hello; // value is 'world';

第二條規則意味着您可以執行以下操作:

function b () { return function () { alert('hello world') } }
var c = b();
c(); // alerts 'hello world';

將規則1和規則2結合使用,可以將以上內容重寫為:

b()(); // alerts 'hello world';

compile('<div my-directive></div>')必須返回具有scope參數的函數。

也許看起來像這樣:

function compile(stringArg){
  return function(scopeArg){
    if(typeof scopeArg === 'object'){
      console.log(stringArg);
    }
  }
}

這與閉包有關。 發生的情況是compile()必須返回一個帶變量的函數,在這種情況下為scope

讓我們看一個簡單的例子:

function adder (first) {
  return function (second) {
    return first + second;
  };
};

adder(2)(3);
// returns 5

var add2 = adder(2);
// add2 now equals function (second) { return 2 + second; }

add2(4);
// returns 6

通常,這樣做的原因是因為您想以多種方式重用函數。 compile的情況下,您可以運行一次compile,然后將其與許多不同的對象(或范圍)一起重用。 另外,您可以使用它進行多種更改。

即,上面的示例可以是adder3adder4等。

編譯可能具有以下行為:

function compile(html) {
  // Some code here to turn string template into something more useable
  return function (scope) {
    // Scope being an object with values to plug into a template
    return DOM_element;
  }
}

暫無
暫無

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

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