views:

517

answers:

2

For whatever reason, Javascript getters/setters for custom objects seem to work with any browser but IE.

Does IE have any other non-standard mechanism for this? (As with many other features)

If not, are there any workarounds to achieve the same functionality?

+2  A: 

IE8 has it through defineProperty, but only for DOM objects. But supposedly, it'll eventually come for JavaScript objects as well.

Nosredna
Eventually? So we'll see it in IE 10? ;)
musicfreak
Interesting - i wasn't aware that this had been added!@musicfreak: you and your sunny optimism...
Shog9
We may see it in IE10, but we'll still be coding for IE6.
Nosredna
@Nosredna: I wish I could vote that up a million times.
musicfreak
+2  A: 

Resig's post references his env.js implementation being the first time he uses the getters and setters methodology you are looking for. The reason this style of works fine for him is because they are not being used in a browser based environment, env.js is focused primarily for server-side JS or scripting environments like Rhino.

To handle browser compatibility as well as focusing on an aspect that the Javascript does very well, use closures for your getter and setter methods to protect object properties.

for example:

foo: function(var){
     var bar = val;
     this.setBar: function( newBar ){ 
           bar = newBar;
     },
     this.getBar: function(){
         return bar;
     }

}

which will result in:

var checkFoo = foo("cool!");
alert(checkFoo.getBar()); //cool!
checkFoo.setBar("nice!");
alert(checkFoo.getBar()); //nice!
strife25