My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, April 28, 2010

Object.defineProperty - A Missed Opportunity

Just a quick post about some clever hack we should probably forget ... make old scripts less obtrusive using new ES5 features.
I am talking bout those guys out there that use scripts with a classic:

onload = function () { ... };
// or
this.onload = ...
// or
window.onload ...
// or
self.onload ...
// etc etc


Apparently WebKit Nightly fires an error when we try to define getters and setters via Object.defineProperty and this is already enough to remove that "hoooraayyyy" for my silly test .... here the code:

Object.defineProperty(this, "onload", (function (self, callback) {
function onload(e) {
while (callback.length) {
callback.shift().call(self, e);
}
}
self.addEventListener ?
self.addEventListener("load", onload, false) :
self.attachEvent("onload", onload)
;
return {
get: function () {
return onload;
},
set: function (onload) {
callback.push(onload);
}
};
}(this, [])));


If we put above snippet before any other script, we can be almost sure that nobody will be able to break anything with classic obtrusive operations:

// test above concept via Chrome and maybe IE8 or others
onload = function () {
alert(1);
};

this.onload = function () {
alert(2);
};


That's it, something that may have been good will probably be just a proof of concept :-)

1 comment:

{Michael : iSkitz} said...

Good stuff Andrea. Shame if it's really not allowed. Gives the simplicity of property setting with override protection. Clever.