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>
輸出:
相關用法
- underscore.js _.bindAll()用法及代碼示例
- Lodash _.method()用法及代碼示例
- Lodash _.sneq()用法及代碼示例
- Lodash _.toQuery()用法及代碼示例
- Lodash _.uniqWith()用法及代碼示例
- Lodash _.xorWith()用法及代碼示例
- Lodash _.head()用法及代碼示例
- Lodash _.remove()用法及代碼示例
- Lodash _.pullAt()用法及代碼示例
- Lodash _.pullAll()用法及代碼示例
- Lodash _.pull()用法及代碼示例
- Lodash _.nth()用法及代碼示例
- Lodash _.takeRight()用法及代碼示例
- Lodash _.take()用法及代碼示例
- Lodash _.sortedLastIndex()用法及代碼示例
- Lodash _.fromPairs()用法及代碼示例
- Lodash _.differenceWith()用法及代碼示例
- Lodash _.castArray()用法及代碼示例
- Lodash _.cloneDeep()用法及代碼示例
- Lodash _.clone()用法及代碼示例
- Lodash _.sampleSize()用法及代碼示例
- Lodash _.find()用法及代碼示例
- Lodash _.zipWith()用法及代碼示例
- Lodash _.zipObject()用法及代碼示例
注:本文由純淨天空篩選整理自skyridetim大神的英文原創作品 Lodash _.bindAll() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。