Javascript node.js中使用lodash的分部类方法?

Javascript node.js中使用lodash的分部类方法?,javascript,node.js,functional-programming,lodash,Javascript,Node.js,Functional Programming,Lodash,我想在node.js中创建一个函数,该函数接受一个整数值,并使用lodash/underline的\uu.partial/\uu.partiOK将其转换为二进制字符串 var _ = require('lodash'); var n = 123456789; console.log(n.toString(2)); // works console.log(Number.prototype.toString.call(n, 2)); // works var toBin = _.partial

我想在node.js中创建一个函数,该函数接受一个整数值,并使用lodash/underline的
\uu.partial
/
\uu.partiOK
将其转换为二进制字符串

var _ = require('lodash');

var n = 123456789;
console.log(n.toString(2)); // works
console.log(Number.prototype.toString.call(n, 2)); // works

var toBin = _.partialRight(Number.prototype.toString.call, 2);
console.log(toBin(n)); // broken
console.log(toBin); // --> [Function: bound]
最后一个中断的实现生成:

/media/data/Dropbox/game-of-spell/node_modules/lodash/dist/lodash.js:957
        return func.apply(thisBinding, args);
                    ^
TypeError: object is not a function

是否可以将
部分化。调用
应用
?如果不是,原因是什么?

要了解发生了什么,您应该尝试这样做:

var call = Number.prototype.toString.call;
call(2);
您将得到
TypeError:undefined不是函数
。您认为
call
是一个函数,错误是错误的。是的,
调用
是一个函数,但此类型错误不是指
调用
,而是指它的上下文(
)。这可能会让人困惑,但调用函数
call
时,会调用它的上下文/这个obejct

您基本上可以这样做:

call.call(function (a) { console.log('wat? This: ', this, '  argument:', a); }, { thisObject: true }, 'im arguemnt');
这将导致:
wat?This:Object{thisObject:true}参数:im arguemnt

但是当调用
call
时,如果没有任何上下文或此对象,则此对象的默认值将是
window
global
对象或严格模式下的
null
。您可以通过以下方式验证此对象的默认值:

function verify() { return this; }; console.log(verify());
它将打印节点中的全局对象和浏览器中的窗口对象

要解决问题,必须将其绑定到其父函数:

var toString = Number.prototype.toString;
var call = toString.call.bind(toString);
或使用lodash绑定:

var call = _.bind(toString.call, toString);
那么这就行了:

var toBin = _.partialRight(call, 2);
您还可以将其缩短为
var toBin=\u0.partiOkable(toString.call.bind(toString),2)

如果您想使用
\uu.partial
,请直接使用绑定:

var print1000 = _.bind(toString.call, toString, 1000);
console.log(print1000(), print1000(2), print1000(8), print1000(16));
您可能还想知道为什么
Number.prototype.toString.call(n,2)
。因为当你调用一个函数作为一个对象的方法时(这里实际上是一个函数),它会把对象作为它的上下文

你可以在这本书里读到更多