JavaScript閉包的實際應用?


在JavaScript中,閉包是一個環境,它幫助我們從內部函式訪問外部函式的作用域。在JavaScript中,當建立一個函式時,閉包也會被建立。換句話說,閉包是一種允許存在於外部函式內部的函式訪問外部函式作用域的方式。在本文中,我們將重點介紹JavaScript中閉包的一些實際應用。

語法

function outerFunction(){
   <initialize property>
   function updateProperty(){
      <update previously initialized property>
   }
   return updateProperty()
}

語法很簡單。閉包只對巢狀函式有效。外部函式將包含其他變數和屬性,這些變數和屬性將由內部函式更新。請注意,這些變數不像全域性變數,它們專門屬於外部函式體。

JavaScript中閉包的使用

考慮一個簡單的例子,我們試圖實現一個計數器應用程式。因此,當用戶執行某些操作時,計數器將一個一個地增加。我們可以透過如下函式實現:

let activity_counter = 0; //a global variable function new_activity() { // function to update the counter value activity_counter++; }

在上面的例子中,全域性變數activity_counter初始化為0,並建立一個函式來將activity_counter的值增加一。這可能是一個解決方案,但主要問題是全域性計數器變數。這個全域性變數可以被其他使用者或指令碼更改。這在我們的應用程式中是不希望的。

我們可以使用閉包來解決這個問題。在下面的程式碼片段中,外部函式:activityCounterClosure()最初建立一個名為new_activity()的函式,該函式增加計數器並從外部函式返回。這段程式碼的妙處在於,現在acc物件儲存了增加計數器的函式,並且由於計數器變數不是全域性的,因此無法從其他地方訪問它。

function activityCounterClosure() { //outer function to implement closure let activity_counter = 0; //property which will be updated through the returned functions function new_activity() { activity_counter++; } return new_activity; } let acc = activityCounterClosure(); acc();

示例

上面的程式碼可以稍微修改一下,如下所示:

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3>Output Console</h3> <p>Output:</p> <div id="output"></div> <div id="opError" style="color : #ff0000"></div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function activityCounterClosure() { //outer function to create the closure let activity_counter = 0; function new_activity() { //function to increase the counter value activity_counter++; } function getCurrentCount() { //function to get current counter value return activity_counter; } return { new_activity: new_activity, getCurrentCount: getCurrentCount, }; } let { new_activity, getCurrentCount } = activityCounterClosure(); new_activity(); content += "Current Count value: " + JSON.stringify(getCurrentCount()) + '<br>'new_activity(); content += "Current Count value (next call): " + JSON.stringify(getCurrentCount()) + '<br>' } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

外部函式返回兩個函式,一個用於增加計數器,另一個用於獲取當前計數器的值。

JavaScript與HTML結合使用閉包

在這裡,我們將看到另一個例子,點選按鈕將建立一個新的html塊。html內容將藉助JavaScript中的閉包屬性建立。讓我們看看下面的例子:

示例

<!DOCTYPE html> <html> <title>Online Javascript Editor</title> <head> </head> <body> <button onclick=addline()>Add a new line</button> </body> <script> function activityCounterClosure() { let activity_counter = 0; function new_activity() { activity_counter++; } function getCurrentCount() { return activity_counter; } return { new_activity : new_activity, getCurrentCount : getCurrentCount, }; } let {new_activity, getCurrentCount} = activityCounterClosure(); function createElement(startTag, endTag) { //return function which adds start and end part of an html document return function (innerHtml) { return `${startTag} ${innerHtml} ${endTag}`; }; } function addline() { // create div block, inside that insert paragraph with current button click value attached with it. new_activity(); var para = document.createElement('div') var blockEl = createElement('<p>', '</p>'); var block = blockEl("Current counter value:" + getCurrentCount()); para.innerHTML = block; document.body.appendChild(para); } </script> </html>

在這個例子中,有兩個閉包函式。一個是增加計數,另一個是透過在段落標籤(<p>)之間新增文字建立html元件。我們在按鈕點選後呼叫這些函式。因此,當點選按鈕時,會在段落(<p>)標籤內生成一行。

結論

在Javascript中,閉包是一個非常有趣且重要的概念。閉包允許從內部函式直接訪問外部函式的作用域。它有很多應用。在本文中,我們同時介紹了一個基於純JavaScript的場景和另一個結合了HTML和JavaScript的場景。使用閉包的一個優點是,它不像全域性變數宣告那樣,因此實際值無法從其他塊更改。

更新於:2022年8月22日

631 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.