如何以编程方式将箭头功能与常规功能区分开?

Gaj*_*jus 5 javascript

箭头函数常规函数之间没有明显区别。

({}).toString.call(function () {})
"[object Function]"
({}).toString.call(() => {})
"[object Function]"
Run Code Online (Sandbox Code Playgroud)

要么

console.dir( (function () {}) )
Run Code Online (Sandbox Code Playgroud)
function anonymous()
    arguments: null
    caller: null
    length: 0
    name: ""
    prototype: Object
    __proto__: ()
    <function scope>
Run Code Online (Sandbox Code Playgroud)
console.dir( (() => {}) )
Run Code Online (Sandbox Code Playgroud)
function anonymous()
    arguments: (...)
    caller: (...)
    length: 0
    name: ""
    __proto__: ()
    <function scope>
Run Code Online (Sandbox Code Playgroud)

两者的行为不同,并且有一个有效的用例可以区分两者。

如何以编程方式将箭头功能与常规功能区分开?

Gaj*_*jus 4

我能想到的最好的方法是使用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);
Run Code Online (Sandbox Code Playgroud)

看:

(function () {}).toString();
"function () {}"

(() => {}).toString();
"() => {}"
Run Code Online (Sandbox Code Playgroud)