Monday, April 12, 2010

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; };
}

1 comment:

  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

    ReplyDelete