Eli Grey

ECMAScript 5 accessors

A while ago, I created a JavaScript library named Xccessors, which implemented the legacy non-standard accessor (getter and setter) methods in IE8. I initially created two different libraries and decided that the library that implemented the legacy methods would be more useful at the time due to no changes needed in a JavaScript program’s code to add accessor support for IE. I never released the second one that implements the ECMAScript 5 (formerly 3.1) standard accessor methods so I’m releasing it now. There can’t be two different libraries with the same “Xccessors” name, so I am also renaming the libraries accordingly to what they implement. The new names are Xccessors Legacy and Xccessors Standard.

Here are two examples of using Object.defineProperty and Object.getOwnPropertyDescriptor:

Using accessors

(function() {
// this creates a document.foo accessor
    var foo = 0;
    Object.defineProperty(document, "foo", {
        get: function() { return foo },
        set: function(x) { return foo += x }
    });
})();
 
document.foo = 5;
(document.foo = 4) === 9;
//Object.getOwnPropertyDescriptor(document, "foo") is {set:[...], get:[...]}

Setting a property

// this is the equivalent of window.foo = "bar";
Object.defineProperty(window, "foo", {value: "bar"});
window.foo === "bar";
Object.getOwnPropertyDescriptor(window, "foo").value === "bar";
window.x = 0;
Object.getOwnPropertyDescriptor(window, "x").value === 0;

Cross-browser accessors

Xccessors is a script I made which implements the legacy methods for defining and looking up object accessors (getters and setters) of objects in JavaScript using ECMAScript 3.1’s accessors standard. This is aimed at adding support for the legacy method in IE8 RC1. Read more on the Xccessors project page. There is also a demo you can try out.

Update: I just tested the script in IE8 RC1 and it seems that IE8 RC1 only supports getters and setters on the DOM and the window object. So as long as you are setting an accessor on the window object or a DOM element, Xccessors should work fine.