以与 jQuery.proxy() 相同的方式调用 lodash _.bind()?

invoking lodash _.bind() in the same way as jQuery.proxy()?

据我从 Lodash documentation 推断,_.bind(func, thisArg, [partials]) 只是 returns 一个 func 的版本,其中 this 的范围被绑定到无论你传递给 thisArg 什么。但是,您需要单独调用该函数,即:

var boundFunction = _.bind(aFunction, aThisTarget);
boundFunction();

有没有一种方法可以像使用 jQuery 的 .proxy() 一样在 lodash 中使用 _.bind() 或不同的函数,因为它会立即调用该函数在传递范围内?

我不会 need/want 将找到的函数保存到变量中,因为它是回调的一部分。我只想(立即)触发一个具有不同范围的函数。即:

this.loadScripts(function() {
    // do something   
}, $.proxy(this, 'doSomethingElse', 'params') );

看看method():

this.loadScripts(function() {

}, _.method(this, 'doSomethingElse', 'params'));

LoDash 的_.bind早期绑定。它需要 函数对象 和上下文来绑定它。

jQuery $.proxy(在您的代码中)是 后期绑定,它需要 key(不是函数本身,而是函数的名称)和上下文。 LoDash 也有后期绑定:_.bindKey.

主要区别在于后期绑定是惰性的:它允许将函数绑定到对象,即使还没有实际函数:

var context = {}
var myMethod = _.bindKey(context, 'myMethod') // object is still empty
context.myMethod = function () { console.log('context:', this); }
myMethod() // will output proper context

它还允许在代码中不重复上下文名称:)

// bind
_.bind(context.myMethod, context)
//     ^ 1               ^ 2

// bindKey
_.bindKey(context, 'myMethod')
//        ^ 1

另一方面,早期绑定更明确,因为它需要实际的函数来绑定,而不是键。