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


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

Lodash是一個JavaScript庫,可在underscore.js之上運行。 Lodash幫助處理數組,字符串,對象,數字等。

lodash中Function的_.bindKey()方法用於創建一個函數,該函數調用object [key]處的方法以及添加到它接受的參數中的部分。

注意:

  • 此方法與_.bind()方法不同,因為它允許綁定函數提及可能被重新解釋或仍然不存在的方法。
  • _.bindKey.placeholder值,在整體構建中默認為(_),用作部分使用的參數的占位符。

用法:

_.bindKey( object, key, partials )

參數:此方法接受上述和以下所述的三個參數:



  • object:它是用於調用方法的對象。
  • key:這是該方法中要使用的 key 。
  • partials:這是要部分應用的論點。它是一個可選參數。

返回值:此方法返回新的綁定函數。

範例1:

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining object parameter of this method 
var obj = { 
  'author':'Nidhi', 
  'welcome':function(greet, mark) { 
    return greet + ' ' + this.author + mark; 
  } 
}; 
  
// Using the _.bindKey() method  
// with its parameters 
var bound_fun = 
  _.bindKey(obj, 'welcome', 'Hello'); 
  
// Calling bound_fun by passing its value 
bound_fun('!!');

輸出:

Hello Nidhi!!

範例2:與占位符一起使用綁定。

Javascript

// Requiring lodash library 
const _ = require('lodash'); 
  
// Defining object parameter of this method 
var obj = { 
  'portal':function(portal, mark) { 
    return 'Welcome to ' + portal + mark; 
  } 
}; 
  
// Using the _.bindKey() method with its 
// parameters and a placeholder 
var bound_fun = 
  _.bindKey(obj, 'portal', _, '!'); 
  
// Calling bound_fun by passing its value 
bound_fun('GeeksforGeeks');

輸出:

Welcome to GeeksforGeeks!

相關用法


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