问题
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?
回答1:
IE8 has it through defineProperty, but only for DOM objects. But supposedly, it'll eventually come for JavaScript objects as well.
回答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!
回答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/
回答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!
来源:https://stackoverflow.com/questions/1077106/javascript-getters-setters-in-ie