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?
JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).
In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.
If no getter or setter for the field exists, a direct access for the field is performed. If a getter exists for the field, it will be executed when trying to read the field from outside. If a setter exists for the field, it will be executed when trying to write the field from outside.
IE8 has it through defineProperty
, but only for DOM objects. But supposedly, it'll eventually come for JavaScript objects as well.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With