Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function.name not supported in IE.

Tags:

javascript

Lately I've become a huge fan of the function.name property.

For example, I've written a function for extending prototypes.

It works in the way of..

Array.give(
    function forEach() { ... }
);

..which would then let you do..

['a', 'b', 'c'].forEach(function () { ... });

This code works great in Chrome, Safari, Firefox, and Opera, but not in IE.

After just a small bit of digging, I realized that to the give function, function.name was just returning undefined, where as in everything else it returned "forEach".

Is there an alternative way to get the name in IE, or should I just fall out of love with this wonderful property?

like image 846
McKayla Avatar asked Aug 01 '11 20:08

McKayla


2 Answers

You can use Object.defineProperty to add support for it on IE9+

// Fix Function#name on browsers that do not support it (IE):
if (!(function f() {}).name) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var name = (this.toString().match(/^function\s*([^\s(]+)/) || [])[1];
            // For better performance only parse once, and then cache the
            // result through a new accessor for repeated access.
            Object.defineProperty(this, 'name', { value: name });
            return name;
        }
    });
}
like image 156
Jürg Lehni Avatar answered Oct 27 '22 01:10

Jürg Lehni


You might be able to parse the function name from calling function.toString [docs]. function.name is not a standard property.

var name = func.toString().match(/^function\s*([^\s(]+)/)[1];

As the comments also say, this is not necessarily a reliable way. Imo passing an object would be easier to read and you could pass several methods at once:

Array.give({
    forEach: function() { ... },
    somethingElse: function() {...}
});
like image 34
Felix Kling Avatar answered Oct 27 '22 02:10

Felix Kling