Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Scoping issue with prototypes and async.forEach

Scoping issue with prototypes and async.forEach

Problem

I have a scope issue that I don't understand.

I have this object with some methods:

FileInfo = (file) ->
   @name = path.basename(file.path);

FileInfo::uploadImage = (filename, callback) ->

FileInfo::handleImage = (version, callback) ->
   # Here I would like to call uploadImage

I am calling handleImage from an async.forEach loop as:

async.forEach options, fileInfo.handleImage,  (err) -

I would like to call uploadImage from within handleImage but I get TypeError: Object # has no method 'uploadImage'

I have tried, inside of handleImage, the following:

this.uploadImage

as well as:

that = this
that.uploadImage

Neither work.

If I call Fileinfo.handleImage outside of the forEach loop it works fine with either this or that.

Problem courtesy of: Yashua

Solution

Change fileInfo.handleImage to fileInfo.handleImage.bind(fileInfo) (assuming fileInfo is an instance of FileInfo).

It is losing the this binding (that is, the value of this when that function is executing, not to be confused with the execution context, see comments) that you expect, because you don't immediately invoke it, just pass a reference to it.

Solution courtesy of: alex

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Scoping issue with prototypes and async.forEach

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×