Underscore.js: how to chain custom functions

前端 未结 7 1388
南方客
南方客 2020-12-31 01:11

Using Underscore.js, I can write the following which returns 42:

_([42, 43]).chain()
    .first()
    .value()

I have custom f

7条回答
  •  鱼传尺愫
    2020-12-31 02:00

    Alright, I'm fresh off of reading the underscore annotated source code for the first time. But I think you can do something like this:

    function double(value) { return value * 2; };
    
    var obj = _([42, 43]).addToWrapper({double:double});
    
    obj.chain()
      .first()
      .double()
      .value();
    

    The syntax/details might not be right, but the core point is this: when you call _([42,43]), you're calling underscore as a function. When you do so, it instantiates a new object and then mixes into that object most of the underscore functions. Then, it returns that object to you. You can then add your own functions to that object, and none of this pollutes the "_" namespace itself.

    That's what the underscore.js code looked like to me. If I'm wrong, I'd like to find out and hopefully someone will explain why.

    EDIT: I've actually been using underscore.js heavily for about a month now, and I have gotten pretty familiar with it. I now know it behaves like I said here. When you call _ as a Constructor function, you get back your own "namespace" (just an object), and you can add things to it with addToWrapper() that show up in your namespace but not in the "global" "_" namespace. So the feature the OP wanted is already built in. (And I have been really impressed with underscore, btw, it is very very nicely done).

提交回复
热议问题