Since Object.__defineGetter__()
has been deprecated I was trying to use Object.defineProperty()
to overwrite the getter function on HTMLSpanElement.prototype.offsetWidth
such that all <span>
elements would return the same value when the offsetWidth property was accessed.
This works perfectly fine in Firefox 28 and IE 11 but in Chrome 33 and 34 (maybe other versions too, I only tried those two) defineProperty()
doesn't seem to be able to overwrite the getter for object prototypes.
Here is my code, HTML:
<span id="testspan">The quick brown fox</span>
Javascript:
Object.defineProperty(HTMLSpanElement.prototype, "offsetWidth", {
get: function(){return 5;},
});
var x = document.getElementById("testspan");
window.alert( x.offsetWidth );
So whenever the offsetWidth of a span object is accessed it should return 5. In Firefox 28 and IE11 it works fine. But in Chrome 33 and 34 it returns the actual width of the span element, in this case 126. As per the ECMA-262 v5 specs (relevant chapter here), assuming I am interpreting it correctly, I should be able re-define the getters and setters for a prototype. Am I missing something? Anyone have any workarounds/hacks for Chrome 34?
Try it on JSFiddle here. Try it in Chrome and Firefox if you have both installed.
A similar question was asked here, although the suggestions by Scimonster don't work in Chrome 34.