views:

155

answers:

2

While trying to port and generally playing around with some non-browser code, I came across getters and setters that looked like normal object properties. Something like this:

js> var o = {
    a: 4,
    get b(){
        return this.a + 3;
    },
    set b(val){
        this.a = val - 3;
    }
};
js> o.a
4
js> o.b
7
js> o.b=10
10
js> o.a
7

This seems to work in recent versions of Rhino and Spidermonkey, but is it possible to implement or simulate the behavior (the defining syntax is less important to me) in JScript (Windows Script Host)?

+1  A: 

According to this article (by John Resig, creator of jQuery), Javascript getters and setters are supported in JScript.NET 8.

JacobM
+1  A: 

The answer is No. Setters and getters are just properties that act like functions, but there is no way to emulate the syntax correctly. I had a half-way concept of emulating getters and setters on HTML elements in <=IE7 using behaviors, but even that turned out to be more difficult than I first imagined it would. Even IE8 only supports getters/setters on DOM objects and not JScript objects, so I think it's something the JScript team need to include, if they ever do.

If only someone had thought to include setters and getters in the original JScript/ECMAScript implementations.

Andy E
I don't really think that getters and setters that look like attributes are a good idea in general because the syntax tends to invoke assumptions when reading the code that make it harder to understand. And it looks as if the claim "Javascript has been a stable language for the last 10 years" has less substance than I thought...
hillu
Just an FYI: in IE8, accessor properties (getters/setters) are implemented on DOM objects only. In a reply to a question asking why this limitation exists, a Microsoft employing said that the feature was a last minute addition and due to time constraints it could not be extended to JScript objects. So fingers crossed, we might see them fully implemented in IE9. JavaScript has been a stable language for a while. It just lacks many of the features you'd normally expect from a language.
Andy E