I would like to override an object property with a function, so that whenever the object’s property is called, it will invoke the function and return the result.
Surely this should be possible in a dynamic language such as JS?
Context:
I’m trying to port some IE-only code to other browsers. The code makes extensive use of the the “Microsoft.XMLDOM” object for parsing and querying XML docs. I’d like to use the standard DOMParser in the non-IE browsers. The problem is that the Microsoft implementation exposes a non-standard ‘text’ property for XML elements, and this property is used extensively in the code-base, I’d like to tack an equivalent function onto the Element prototype.
Element.prototype.text = function() {...}
doesn’t work since when the code-base does ‘myelem.text’, it doesn’t actually run the function, it just returns a pointer to it.
What should I do to make this work?
In modern enough Javascript (e.g. anything other than IE),
Object.definePropertycan do just that.