3

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.

Community
  • 1
  • 1
CoryTobin
  • 31
  • 1
  • 4
  • There was an edit in the Question u linked to [THANKS!] deleting the `offsetWidth` attribute out of EVERY OBJECT would to the trick - That is the best solution I could find. (force Chrome to lookup the attribute in the prototype chain) – HLL May 28 '14 at 15:25

1 Answers1

0

Modifying a property

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

As described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

and yes deleteing the offsetWidth from the instance will force the prototype check and will return 5 :)

bluehipy
  • 381
  • 2
  • 5