Javascript getters/setters in IE?

11,002

Solution 1

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

Solution 2

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!

Solution 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/

Solution 4

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!

Share:
11,002
OB OB
Author by

OB OB

Updated on June 03, 2022

Comments

  • OB OB
    OB OB about 2 years

    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?

  • Sasha Chedygov
    Sasha Chedygov almost 15 years
    Eventually? So we'll see it in IE 10? ;)
  • Shog9
    Shog9 almost 15 years
    Interesting - i wasn't aware that this had been added! @musicfreak: you and your sunny optimism...
  • Nosredna
    Nosredna almost 15 years
    We may see it in IE10, but we'll still be coding for IE6.
  • Ed Sykes
    Ed Sykes about 12 years
    is this still good advice 3 years later? Looking at this compatibility table seems like support in ie is better: kangax.github.com/es5-compat-table
  • talegna
    talegna almost 10 years
    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.