chenb•log

I don’t mind if I’m incomprehensible

JavaScript "with" Cheesy Hack

leave a comment »

code, pre { font-size: 1.3em; } 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?

Advertisements

Written by Barry

October 24, 2007 at 6:25 pm

Posted in Nerdy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: