之间没有明显的区别箭头函数 and a 常规功能.
({}).toString.call(function () {})
"[object Function]"
({}).toString.call(() => {})
"[object Function]"
or
console.dir( (function () {}) )
function anonymous()
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: ()
<function scope>
console.dir( (() => {}) )
function anonymous()
arguments: (...)
caller: (...)
length: 0
name: ""
__proto__: ()
<function scope>
不过,两者的行为不同,并且有一个有效的用例可以区分两者。
如何以编程方式区分箭头函数和常规函数?
我能想到的最好的方法是使用toString
:
let isArrowFunction;
isArrowFunction = (fn) => {
console.log(fn.toString());
return fn.toString().indexOf('function') !== 0;
};
console.log(isArrowFunction(() => {}) === true);
console.log(isArrowFunction((foo: string) => {}) === true);
console.log(isArrowFunction(function () {}) === false);
See:
(function () {}).toString();
"function () {}"
(() => {}).toString();
"() => {}"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)