最近我成了function.name房产的忠实粉丝.
例如,我编写了一个扩展原型的函数.
它的工作方式..
Array.give(
function forEach() { ... }
);
Run Code Online (Sandbox Code Playgroud)
..然后会让你做..
['a', 'b', 'c'].forEach(function () { ... });
Run Code Online (Sandbox Code Playgroud)
此代码适用于Chrome,Safari,Firefox和Opera,但不适用于IE.
在进行了一小部分挖掘之后,我意识到对于give函数来说,function.name只是返回undefined,就像返回的其他东西一样"forEach".
有没有另一种方法可以在IE中获得该名称,或者我是否会对这个美妙的财产失去爱意?
Jür*_*hni 32
您可以使用Object.defineProperty在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;
}
});
}
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 21
您可以通过调用function.toString [docs]来解析函数名称.function.name是不是一个标准特性.
var name = func.toString().match(/^function\s*([^\s(]+)/)[1];
Run Code Online (Sandbox Code Playgroud)
正如评论所说,这不一定是一种可靠的方式.Imo传递一个对象会更容易阅读,你可以一次传递几个方法:
Array.give({
forEach: function() { ... },
somethingElse: function() {...}
});
Run Code Online (Sandbox Code Playgroud)
我认为你的.give()解决方案有点......很难.有什么不对:
Array.prototype.forEach = function () { ... };
Run Code Online (Sandbox Code Playgroud)
?
但实际上,在提供自己的方法之前,你应该检查这种方法是否存在:
Array.prototype.forEach = Array.prototype.forEach || function () { ... };
Run Code Online (Sandbox Code Playgroud)
由于其他人将在这里被引导想知道function.name,有一种方法来获取名称(显然,它不适用于匿名函数):
function getFnName(fn) {
return (fn.toString().match(/function (.+?)\(/)||[,''])[1];
}
Run Code Online (Sandbox Code Playgroud)