diff --git a/index.js b/index.js index b2b272c..2bed355 100644 --- a/index.js +++ b/index.js @@ -19,12 +19,12 @@ module.exports = thunkify; * @api public */ -function thunkify(fn){ +function thunkify(fn, ctx){ assert('function' == typeof fn, 'function required'); return function(){ var args = new Array(arguments.length); - var ctx = this; + ctx || (ctx = this); for(var i = 0; i < args.length; ++i) { args[i] = arguments[i]; diff --git a/test/index.js b/test/index.js index 48c63d8..593013d 100644 --- a/test/index.js +++ b/test/index.js @@ -108,4 +108,23 @@ describe('thunkify(fn)', function(){ }); }); }) + + it('should preserve passed context', function(done){ + function Foo() { + this.bar = 'bar'; + this.fn = function (callback) { + callback(null, this.bar); + } + } + + var foo = new Foo(); + + fn = thunkify(foo.fn, foo); + + fn()(function (err, a) { + assert('bar' == a); + done(); + }); + }) + }) \ No newline at end of file