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?

Chris Pietschmann
  • 29,502
  • 35
  • 121
  • 166
OB OB
  • 3,289
  • 6
  • 21
  • 16
  • 1
    ie9 and ie10 support this now: http://kangax.github.com/es5-compat-table/ – Ed Sykes May 30 '12 at 15:59
  • They're supported on on object literals, but not object prototypes in IE :(. http://robertnyman.com/javascript/javascript-getters-setters.html#regular-getters-and-setters – roguenet Jan 15 '13 at 19:21

4 Answers4

8

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

Shog9
  • 156,901
  • 35
  • 231
  • 235
Nosredna
  • 83,000
  • 15
  • 95
  • 122
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!
Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
linusthe3rd
  • 3,455
  • 3
  • 28
  • 43
  • 3
    is this still good advice 3 years later? Looking at this compatibility table seems like support in ie is better: http://kangax.github.com/es5-compat-table/ – Ed Sykes May 30 '12 at 15:57
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/

MandoMando
  • 5,215
  • 4
  • 28
  • 35
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!

  • 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 08 '14 at 11:23