[JS] HOWTO: Monkey patch IE for support for Function.name
Written byFriday, 09 March 2012 - 01:00
atLast updated: Friday, 08 June 2012 - 22:49
One of the better ways of detecting an object’s type name in Javascript
is obj.constructor.name
. It’s also the way that the Drupal states API does it.
Unfortunately, Internet Explorer doesn’t support the non-standardised, though
rather standard Function.name
property.
So, here’s how to monkey patch it into IE9 and above. IE8 doesn’t support
defineProperty
properly and earlier versions don’t support
it at all so those versions are still unsupported by this method.
/**
* Hack in support for Function.name for browsers that don't support it.
* IE, I'm looking at you.
**/
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function() {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((this).toString());
return (results && results.length > 1) ? results[1].trim() : "";
},
set: function(value) {}
});
}