Getters and setters with JavaScript – code samples and demos

Not many people know it, but you can use “real” getters and setters in JavaScript if you want to.

De-facto offerings

Firefox 2.0+, Safari 3.0+, Google Chrome 1.0+ and Opera 9.5+ support a de-facto way of getters and setters:

var lost = {
	loc : "Island",
	get location () {
		return this.loc;
	set location(val) {
		this.loc = val;
lost.location = "Another island";

// lost.location will now return "Another island"

And on DOM elements:

HTMLElement.prototype.__defineGetter__("description", function () {
	return this.desc;
HTMLElement.prototype.__defineSetter__("description", function (val) {
	this.desc = val;
document.body.description = "Beautiful body";

// document.body.description will now return "Beautiful body";

Via Object.defineProperty

The future, and ECMAScript standardized way, of extending objects in all sorts of ways is through Object.defineProperty. This is how Internet Explorer chose to implement getters and setters, but it is unfortunately so far only available in Internet Explorer 8, and not in any other web browser. Also, IE 8 only supports it on DOM nodes, but future versions are planned to support it on JavaScript objects as well.

Getter and setters in IE8+:

Object.defineProperty(document.body, "description", {
	get : function () {
		return this.desc;
	set : function (val) {
		this.desc = val;
document.body.description = "Content container";

// document.body.description will now return "Content container"

Test cases

I’ve put together test cases in my JavaScript test site, where you can see JavaScript web browser compatibility tables and code samples and demos for getters and setters together with Object.defineProperty.


Kudos for Microsoft to take the step to implement Object.defineProperty, although it’s sad that it’s only available for DOM elements as of now. Also, just as we have consistency between web browsers with innerHTML, XMLHTTPRequest etc, it would have been really desirable if Microsoft would have supported the several years-old de-facto way of implementing getters and setters.

So, Microsoft slowly treads forward, which is good, but at the same unfortunately gives us yet another case of doing something different to make it work in Internet Explorer (more about this can be read in ECMAScript getters and setters interoperability).

Anyway, getters and setters are here today, and with some feature detection, you can use it to implement some nice things. Happy coding! :-)

Posted in Developing,JavaScript,Technology,Web browsers |

Leave a Reply

Your email address will not be published. Required fields are marked *