下面是另一個混入實現:
function myResult(obj, path, defaultValue) {
// Find any arguments beyond what's normally
// passed to result().
var args = _.drop(arguments, 3);
// We need to know upfront whether or not this
// is a function we're dealing with.
var isFunc = _.isFunction(_.get(obj, path));
// If this is a function, and there's arguments
// to apply, then use spread() and bindKey() to
// return the result of calling the method with arguments.
// Otherwise, it's just a plain call to result().
if (isFunc && args.length) {
return _.spread(_.bindKey(obj, path))(args);
} else {
return _.result(obj, path, defaultValue);
}
}
_.mixin({ myResult: myResult });
的想法是,我們只需要應付增加的情況下path
是一個函數和額外的參數傳遞。否則,我們恢復到基本的result()
實施。
_.myResult(object, 'test');
// → undefined
_.myResult(object, 'test', 15);
// → 15
_.myResult(object, 'cheese', 'wine');
// → "crumpets"
_.myResult(object, 'stuff');
// → "balderdash"
_.myResult(object, 'stuff', null, true);
// → "nonsense"
該文檔似乎沒有顯示任何方式來完成此https://lodash.com/docs#result(如果我理解正確),所以我的猜測是,這不支持。您可以在這裏詢問https://github.com/lodash/lodash/issues以確定,或者甚至要求它作爲附加功能。 – Xotic750