JavaScript “with” Cheesy Hack

— Barry on October 24, 2007 at 6:25 pm

The quotation marks around with are not unnecessary because this is about the JavaScript keyword.

Douglas Crockford said in his “The JavaScript Programming Language” video lecture not to use with, because the scope gets all confused. Or something. But since I’m not a senior JavaScript Architect at Yahoo!, I can cheesy hack all I want.

Here is the relevant code:

with(this) {
  GEvent.addListener(polygon,
                     'click',
                     function(point) { clicked(OMap.getMap(), point); }
  );
}

That code is in a public class method (drawPolygon). I need with for the clicked method used in the anonymous function for handling the click event.

Without with, clicked won’t resolve to anything. I can’t use this.clicked, since this will be referring to the clicked polygon, not the object drawPolygon and clicked belong to.

Some of you might be thinking “well, have you tried copying clicked into drawPolygon’s scope with something like var clicked = this.clicked;“? Well done, sir. You’ve just won some internets for your trouble.

Unfortunately, that doesn’t work in this case. It fixes the scope with clicked in the anonymous function. But the problem is that this is used in the clicked method, and clicked’s this will reference the wrong object. FAIL.

I wonder: What Would Doug Do?

0 Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. | chenb•log