Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable as an object and a function

I am trying to mock the times function from the JavaScript library Underscore.js.

This function accepts two syntaxes :

_.times(3, function(n) {
    console.log("hello " + n);
});

and

_(3).times(function(n) {
    console.log("hello " + n);
});

So far I succeeded to mock the first one by creating an _ object like this :

var _ = {
    times: function(reps, iteratee) {
        // a loop
    }
};

And the second syntax by creating an _ function which returns an object :

function _(n) {
    return {
        times: function(iteratee) {
            // a loop
        }
    };
}

But I can't use these 2 methods together. I need to find a way that will allow both syntaxes. Do you have any idea how I could use the _ character as an object as well as a function ?

like image 527
Seeven Avatar asked Jul 19 '15 21:07

Seeven


2 Answers

You should be able to combine two syntaxes like this:

var _ = (function() {

    var times = function(n, iteratee) {
        // a loop
    };

    function _(n) {
        return {times: function(iteratee) {
            return times(n, iteratee);
        }}; // or shorter: {times: times.bind(null, n)}
    }

    _.times = times;

    return _;
})();

Here you benefit from the fact that functions are also objects and hence can have properties.

like image 61
dfsq Avatar answered Oct 06 '22 13:10

dfsq


Functions are objects in Javascript, so you could just do something like this:

var _ = function(a,b) { /* ... */ };
_.times = _;
like image 24
Wander Nauta Avatar answered Oct 06 '22 12:10

Wander Nauta