【问题标题】:partial class methods in node.js using lodash?node.js中的部分类方法使用lodash?
【发布时间】:2014-05-29 08:44:10
【问题描述】:

我想在 node.js 中创建一个函数,它接受一个整数值并使用 lodash/underscore 的 _.partial/_.partialRight 将其转换为二进制字符串。

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

是否可以偏分.call.apply?如果不是,为什么?

【问题讨论】:

    标签: javascript node.js functional-programming lodash


    【解决方案1】:

    要了解正在发生的事情,您应该尝试这样做:

    var call = Number.prototype.toString.call;
    call(2);
    

    您将收到TypeError: undefined is not a function。你在想call是一个函数,报错是错的。是的,call 是一个函数,但这个 TypeError 不是在谈论 call,而是在谈论它的上下文(this)。这会令人困惑,但函数 call 在调用时会调用它的上下文/此对象。

    你基本上可以这样做:

    call.call(function (a) { console.log('wat? This: ', this, '  argument:', a); }, { thisObject: true }, 'im arguemnt');
    

    这将导致:wat? This: Object {thisObject: true} argument: im arguemnt

    但是当call在没有任何上下文或这个对象的情况下被调用时,那么在严格模式下,默认的这个对象将是windowglobal对象或null。您可以像这样验证默认的 this 对象:

    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 = _.partialRight(toString.call.bind(toString), 2);

    如果要使用_.partial,则直接使用bind:

    var print1000 = _.bind(toString.call, toString, 1000);
    console.log(print1000(), print1000(2), print1000(8), print1000(16));
    

    您可能还想知道为什么Number.prototype.toString.call(n, 2)。因为当你将函数作为对象的方法调用时(实际上是这里的函数),它会将对象作为它的上下文。

    您可以在answer of mine 中阅读更多内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      相关资源
      最近更新 更多