當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Lodash _.bindAll()用法及代碼示例

Lodash _.bindAll()方法用於綁定對象上的多種方法。每個方法都有一個方法名稱。使用事件處理程序很方便。

用法:

_.bindAll(object, methodNames)

參數:此方法接受上麵提到和下麵描述的兩個參數:

  • object:它是包含不同方法和函數的對象。
  • methodNames:它是對象中存在的方法的名稱。

返回值:它返回一個對象。

注意:此方法未設置綁定函數的“length”屬性。



以下示例說明了JavaScript中的Lodash _.bindAll()方法:

範例1:

Javascript

<!DOCTYPE html> 
<html> 
 
<head> 
    <script src=
"https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js">
    </script>
</head> 
 
<body> 
    <button id="button">button</button> 
 
    <script type="text/javascript"> 
 
        var object={ 
                label :'GeeksforGeeks', 
                click:function(){ 
                    console.log( 'clicked:' + this.label); 
                    }, 
                hover:function(){ 
                    console.log( 'hovering:' + this.label); 
                    } 
                }; 
 
        // Using bindAll() method of lodash 
        _.bindAll(object, 'click', 'hover'); 
 
        // When the button is clicked,  
        // this.label will have the correct value.
        let btn=document.querySelector("#button"); 
         
        btn.addEventListener('click', object.click); 
        btn.addEventListener('click', object.hover);  
    </script> 
</body> 
 
</html>

輸出:

範例2:

Javascript

<!DOCTYPE html> 
<html> 
 
<head> 
    <script src=
"https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js">
    </script>
</head> 
 
<body> 
    <button id="button">button</button> 
    <script type="text/javascript">  
        var object={ 
            printNum:()=>{ 
                for(let i=0; i<5; i++) 
                    console.log(i+" geeksforgeeks") 
                }, 
            func:function(){ console.log( 
                'Function:' + this.printNum); 
                }, 
            output:function(){ "Output:"+this.printNum(); 
                } 
            }; 
         
        // Using bindAll() methof of lodash 
        _.bindAll(object, 'func', 'output'); 
 
        // When the button is clicked  
        let btn=document.querySelector("#button"); 
         
        btn.addEventListener('click', object.func); 
        btn.addEventListener('click', object.output); 
    </script> 
</body> 
 
</html>

輸出:

參考:https://docs-lodash.com/v4/bind-all/

相關用法


注:本文由純淨天空篩選整理自skyridetim大神的英文原創作品 Lodash _.bindAll() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。