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; |