Setters/getters for Internet Explorer 9

Past entries

Hello everyone,

Today I'll post a quick article dealing with Internet Explorer 9 compatibility.

As I am currently developing a new HTML5 game, I checked if it was actually working on IE9, and I was quite disappointed to see that my Javascript framework wasn't working. After taking a look at the debug console, I realized that it was "only" a matter of setters and getters.

After some research, I found that __defineSetter__ and __defineGetter__ functions were not included in the ECMAScript standard, and therefore were not supported on IE9 (contrary to other major browsers). Hopefully, the actual standard does include a defineProperty method, which is supported by IE9.

I then found a workaround on this blog post. This solution is quite good, but it lacks support for __lookupSetter__ and __lookupGetter__. That's why I wrote my own one, highly inspired by the IE team's.

Here it is :

try {
   if (!Object.prototype.__defineGetter__ &&
        Object.defineProperty({},"x",{get: function(){return true}}).x) {
		
		// Setter	
		Object.defineProperty(
			Object.prototype, 
			"__defineSetter__",
			{
				enumerable: false, 
				configurable: true,
				value: function(name,func){
					Object.defineProperty(this,name,{set:func,enumerable: true,configurable: true});
					
					// Adding the property to the list (for __lookupSetter__)
					if(!this.setters) this.setters = {};
					this.setters[name] = func;
				}
			}
		);
		
		// Lookupsetter
		Object.defineProperty(
			Object.prototype, 
			"__lookupSetter__",
			{
				enumerable: false, 
				configurable: true,
				value: function(name){
					if(!this.setters) return false;
					return this.setters[name];
				}
			}
		);
		
		// Getter	
		Object.defineProperty(
			Object.prototype, 
			"__defineGetter__",
			{
				enumerable: false, 
				configurable: true,
				value: function(name,func){
					Object.defineProperty(this,name,{get:func,enumerable: true,configurable: true});
					
					// Adding the property to the list (for __lookupSetter__)
					if(!this.getters) this.getters = {};
					this.getters[name] = func;
				}
			}
		);
		
		// Lookupgetter
		Object.defineProperty(
			Object.prototype, 
			"__lookupGetter__",
			{
				enumerable: false, 
				configurable: true,
				value: function(name){
					if(!this.getters) return false;
					return this.getters[name];
				}
			}
		);
		
   }
} catch(defPropException) {/*Do nothing if an exception occurs*/};

It looks a bit complex, but in fact it is very simple. It only creates the methods when they're not implemented.

And by the way, I also noticed that IE did not include the "name" field for functions, which is a bit sad, so here is another workaround :

(function(){
	if(!Function.name){
		Function.prototype.__defineGetter__('name',function(){
			return (this.toString().split(/[s(]/g))[1];
		});
	}
})();

I hope they will be useful.

< Generic documentation script
Haunted Gardens teaser >