Monday, March 29, 2010

blog post patch

Ok, I wasn't 100% correct in my last post. There was something I didn't consider.

Where I said:

Considering this class:


class Obj {
private String item;
public void setItem(String str) {
item = str;
}
public String getItem() {
return item;
}
}


and consider this usage:


Obj thing = new Obj();
thing.setItem("this has been set");
println(thing.getItem()); // prints "this has been set"
println(thing.item); // prints undefined, as it's not been used yet


Everything working as intended, until I try this:


thing.item = "if you see this, it's broken";
println(thing.getItem()) // prints "if you see this, it's broken" :(

I was wrong, that should work as I originally had hoped, but what was happening was processing.js would wrap it inside a with(this){...} function, which I'm still looking into, but it was doing things that I figured was just normal JavaScript, so I over looked it.

Here are some comparing classes, to illustrate what I mean:

// What should, and does work as intended.
function Obj() {
var privateMember = "hidden";
this.getMember = function() {
return privateMember;
}
}
var obj = new Obj();
alert(obj.getMember()); // alerts "hidden"
obj.privateMember = "not hidden";
alert(obj.getMember()); // alerts "hidden" :D

Now, what processing.js does:

// Does not work as intended.
function Obj() { with (this) { // This is the only change
var privateMember = "hidden";
this.getMember = function() {
return privateMember;
}
}}
var obj = new Obj();
alert(obj.getMember()); // alerts "hidden"
obj.privateMember = "not hidden";
alert(obj.getMember()); // alerts "not hidden" :(

Now, why not yank "with(this){...}" right out of there? I don't know what it's doing, yet. More on that later. But I'm hopeful to say I have a pretty solid direction.

No comments:

Post a Comment