with(this) { … } // no more

Here is the source, and an example for processing.js with “with(this) { … }” removed.

I was having issues using the new getters and setters. What was happening was considering this JavaScrpt class.


function Foo() {
this.value = 0;
__defineGetter__('value', function() { return this.value; });
__defineSetter__('value', function(x) { this.value = x; });

this.getValue = function(){ return value; };
this.setValue = function(x) { value = x; };
}

The this. keywords scope wasn’t as intended. It was actually referring to the getter or setters, and not the object that uses it. I solved this by putting it into a closure, and passing the object I wanted the getters and setters to be added to, like so:


function Foo() {
this.value = 0;
__defineGetter__('value', (function(obj) { return function() { return obj.value; };})(this));
__defineSetter__('value', (function(obj) { return function(x) { obj.value = x; };})(this));

this.getValue = function(){ return value; };
this.setValue = function(x) { value = x; };
}
Advertisements

One Response to “with(this) { … } // no more”

  1. Awesome! I can't wait to get your stuff + mine landed. One comment: in the getValue and setValue functions, don't work with value (that adds an extra layer of indirection by using the getter/setter). Instead, use this.value.Dave

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: