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 :-)

Comments

Popular posts from this blog

8 Things you should not be afraid of as a Developer

News

Why REST is so important