Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getters/setters in IE?

Tags:

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?

like image 592
OB OB Avatar asked Jul 02 '09 23:07

OB OB


People also ask

Are there getters and setters in JavaScript?

JavaScript Accessors (Getters and Setters)ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Object Accessors (Computed Properties).

How do setters work in JavaScript?

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.

What will happen if you bind to a property for which no public setter is available?

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.


2 Answers

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

like image 164
Nosredna Avatar answered Sep 16 '22 15:09

Nosredna


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!
like image 28
linusthe3rd Avatar answered Sep 19 '22 15:09

linusthe3rd