如何以编程方式区分箭头函数和常规函数? [英] How to programmatically distinguish an arrow function from a regular function?
本文介绍了如何以编程方式区分箭头函数和常规函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
({}).toString.call(function () {})
"[object Function]"
({}).toString.call(() => {})
"[object Function]"
或
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>
两者的行为不同但有效用例能够区分两者。
The behaviour of the two is different though and there is a valid use case for being able to tell the two apart.
如何以编程方式区分箭头函数和常规函数?
How to programmatically distinguish an arrow function from a regular function?
推荐答案
我能想到的最好的就是使用 toString
:
The best I can think of is using 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);
参见:
(function () {}).toString();
"function () {}"
(() => {}).toString();
"() => {}"
这篇关于如何以编程方式区分箭头函数和常规函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文