20

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

4 Answers 4

8

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

3
  • 4
    Eventually? So we'll see it in IE 10? ;) Jul 2, 2009 at 23:07
  • Interesting - i wasn't aware that this had been added! @musicfreak: you and your sunny optimism...
    – Shog9
    Jul 2, 2009 at 23:10
  • 27
    We may see it in IE10, but we'll still be coding for IE6.
    – Nosredna
    Jul 2, 2009 at 23:25
5

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 JavaScript does very well, use closures for your getter and setter methods to protect object properties.

For example:

foo: function(val) {
     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!
1
3

A solution for IE6+ is available that uses the onpropertychange event and the newer spec defineProperty. The slight catch is that you'll need to make your variable a dom object.

Full details:

http://johndyer.name/native-browser-get-set-properties-in-javascript/

1

For old IE browsers you can also use VB to emulate getter and setter Take a look at this getters & setters for all IE with cross browser VBClass!

1
  • You might want to add the core detail of the link you've provided. As it (your response) stands, although correct, should the url you are linking to become unavailable your it will become less helpful.
    – talegna
    Sep 8, 2014 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.