javascript - Accessing parent function when using Function.prototype methods -
i'm playing around function.prototype learning exercise , trying make generic curry method used this:
// old function var myfn = function(arg1, arg2) { console.log(arg1, arg2); }; // curry parameters , return new function var myfncurry = myfn.curry("a"); // call curried function, passing in remaining parameters myfncurry("b"); // outputs: b
it's straight forward implement feature function rather method using following approach:
var curry = function(fn) { var slice = array.prototype.slice, args = slice.call(arguments, 1); return function() { fn.apply(this, args.concat(slice.call(arguments))); }; }; // example var myfncurry = curry(myfn, "a"); myfncurry("b"); // outputs: b
however, wanted able utilise function prototype, this:
function.prototype.curry = function() { var slice = array.prototype.slice, args = slice.call(arguments); return function() { // if call curry this: myfn.curry() // how can reference myfn here? ???.apply(this, args.concat(slice.call(arguments))); }; };
i'm not sure how reference myfn function (denoted ??? above) curry method being called from.
is there way access parent function in circumstance?
cheers,
ian
you're calling curry in context of function object (myfn.curry
), , therefore inside of curry this
refers function. inner function called in context of global object, that's why need store reference outer function in closure.
function.prototype.curry = function() { var self = this, args = [].slice.call(arguments) return function() { return self.apply(this, args.concat([].slice.call(arguments))); } }
Comments
Post a Comment