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.

Introducing JS3
Curl Requests & HTTP Authentication in Python
SweepSVN – Remove .SVN directories recursively from any project with the click of a button
Setting up Xcode to Compile & Upload to an Arduino ATMega328 (Duemilanove)
Extract EXIF data using PHP to display GPS-tagged Images in Google Maps
Format Twitter ‘created_at’ Date with Javascript
Dynamically Create an Image in Flash and Save it to the Desktop or Server
Playing with P5Sunflow
Stussy & Nike NSW pick up CommArts Webpick of the Day 11/12 & 11/18
Getting Started with OpenFrameworks
Moving Forward & Setting New Goals
Easy Full-Screen Gradients in Flash – AS3
AS3 Image Batch Loader with PHP Directory Browsing
Tracy Chapman wins FWA!
New Work – Tracy Chapman
Transform Tool – Drag, Scale and Rotate in Flash at Runtime
Upload BitmapData Snapshot to Server in AS3
Top Five Things You Need to Know Before Driving Across The United States
Starting Over