Cross Browser Getter & Setter Methods in JavaScript

While working on JS3 over the weekend, I discovered that the __defineGetter__ & __defineSetter__ method calls I had implemented were breaking in Internet Explorer.

Error: Object doesn’t support property or method ‘__defineGetter__ ‘

The fix I found is to instead implement the new defineProperty method introduced in EcmaScript5.

defineProperty simply takes the Object you want to add a getter and/or setter to, the name of the property and an Object that contains your actual getter & setter functions that you’d like to have called when the property value is set or retrieved.

var obj = {};
var funcs = {get:function(){}, set:function(){}};
Object.defineProperty(obj, "name", funcs);

Imagine I have a Person Object and I’d like to associate a getter & setter with its name property.

function Person()
{
 // set a default value //
    this.__name = 'John';
 // add getter & setter methods //
    Object.defineProperty(this, "name", {
        get: function() {
        // additional getter logic
            return this.__name;
        },
        set: function(val) {
        // additional setter logic
            this.__name = val;
        }
    });
}
 
var p = new Person();
console.log(p.name); // 'John'
p.name = 'Stephen';
console.log(p.name); // 'Stephen'

I’ve tested this and found it to work on all the major browsers including Internet Explorer 9.