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

Does named closures pollute the global/window object?

Does named closures pollute the global/window object?

Problem

According to this node style guide, giving closures a name is a good practice:

Right

req.on('end', function onEnd() {
  console.log('winning');
});

Wrong

req.on('end', function() {
  console.log('losing');
});

However, I'm used to thinking of the

function someName() { someStatements(); }

...syntax as something that creates a global variable, someName or window.someName for that function. Is this really a good practice, or is that a very bad style guide?

Problem courtesy of: kornfridge

Solution

In node.js, what you describe does not pollute the global context.

Given:

function someName() { someStatements(); }

global.someName will be defined. The following however:

setTimeout(function someName() { someStatements(); }, 500);

Will not set global.someName.

It seems to be just a matter of aesthetics. I tested this with node.js v0.8.4, but the same behaviour should be present in most modern browsers.

Solution courtesy of: Mahn

Discussion

View additional discussion.



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

Share the post

Does named closures pollute the global/window object?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×