Jan
Jan

Reputation: 3401

How does this js snippet work?

function thunkify(fn) {
    var args = [].slice.call( arguments, 1 );
    return function(cb) {
        args.push( cb );
        return fn.apply( null, args );
    };
}

so [] returns an Array object. then slice.call creates a new array with the contents of the arguments starting from 1 if i'm right.

but then how does function(cb) work? it where do you get the cb?

Upvotes: -1

Views: 56

Answers (2)

sagie
sagie

Reputation: 1777

args is now an array holding all thunkify args (except the first one as you said). that args array, than gets a cb function pushed every time the returned function is called (thats closure, the returned function has access to the args from the thunkify function).

var myfn = thunkify(fn, 1, 2, 3); //now args is [1, 2, 3]; myfn(4); //now args is [1, 2, 3, 4] and fn is called with that array

Upvotes: 2

Quentin
Quentin

Reputation: 943571

function(cb) { ... } creates a function.

cb is the argument passed to it.

You get it when the function is called.

var thunkified = thunkify(someFunction);
thunkified("the value of cb");

Upvotes: 2

Related Questions