Best way to create class getter/setters in Javascript?

Edward Tanguay picture Edward Tanguay · Dec 15, 2010 · Viewed 15.6k times · Source

Coming from C#/PHP, I would like to have full getters/setters on the classes (functions) that I create with Javascript.

However, in much of the Javascript code I have encountered, getters and setters are not used, rather simple public variables.

I was pleased to find John Resig's article on getters and setters, but some comments on it which state that some browsers "do not support getters and setters" which is confusing to me since they are not a "feature" of Javascript but more of a simple pattern which uses basic Javascript syntax. This article was also written in 2007 so it could be outdated by now.

What is the current state of getters and setters in Javascript? Are they indeed "supported" by all browsers today (whatever that means)? Are they a useful programming pattern for Javascript or are Javascript classes (being functions) better off with public variables? Is there a better way to implement them than the following?

$(document).ready(function() {
    var module = new Module('idcode');
    module.set_id_code('new idcode');
    module.set_title('new title');
    $('body').html(module.get_id_code()+': '+module.get_title());
});

function Module(id_code, title) {
    var id_code = id_code;
    var title = title;

    //id_code
    this.get_id_code = function() {
        return id_code;
    }
    this.set_id_code = function(value) {
        id_code = value;
    }

    //title
    this.get_title = function() {
        return title;
    }
    this.set_title = function(value) {
        title = value;
    }
}

Answer

Tim Down picture Tim Down · Dec 15, 2010

Firefox, Safari, Chrome and Opera (but not IE) all have the same non-standard getter and setter mechanism built in. ECMAScript 5 includes a different syntax that is currently making its way into browsers and will become the standard in future. IE 8 already has this feature, but only on DOM nodes, not regular native JavaScript objects. This is what the syntax looks like:

var obj = {};

Object.defineProperty(obj, "value", {
    get: function () {
        return this.val;
    },
    set: function(val) {
        this.val = val;
    }
});