【问题标题】:How to programmatically distinguish an arrow function from a regular function?如何以编程方式区分箭头函数和常规函数?
【发布时间】:2015-12-12 19:46:06
【问题描述】:

arrow functionregular 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>

虽然两者的行为不同,但有一个有效的用例可以区分两者。

如何以编程方式区分箭头函数和常规函数?

【问题讨论】:

  • 所以基本上有一些方法可以知道是否使用匿名函数或箭头函数作为参数?我不认为有类似的东西可用,但也许有?
  • 您的答案可能在 this 对象中,因为常规函数将 this 对象分配给自身,但箭头函数将 this 对象分配给箭头函数之外的 this 对象
  • 为什么在运行时需要它? “虽然两者的行为不同” --- 相同:它们都接受参数并返回结果。
  • @zerkms 这些只是定义函数行为的两个特性。正如其他人指出的那样,还有更多,例如箭头函数中的词法this
  • @GajusKuizinas 没错,但这在运行时对您来说并不重要。作为客户端,您对函数唯一能做的就是传递参数并检索结果。从这个角度来看,它们的行为相同。您将把它应用到什么实际案例中?

标签: javascript


【解决方案1】:

我能想到的最好的方法是使用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();
"() => {}"

【讨论】:

【解决方案2】:

嗯,要求有点奇怪,但我做了一些测试:

typeof (() => {}).prototype === "undefined"

true,而:

typeof (function () {}).prototype === "undefined"

false,所以:

function isArrow(x)
{
  return typeof (x.prototype) === "undefined"
}

在这里提琴:https://jsfiddle.net/87kn67ov/

【讨论】:

  • 我可以在 Chrome 中复制它,虽然我不明白它是如何工作的,尤其是。鉴于存在(() =&gt; {}).call 和其他Function 原型方法。
  • 我真的不知道,只是转储了一些匿名函数和一些箭头函数并检查了差异。根据:tc39wiki.calculist.org/es6/arrow-functionsArrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method,但这并不能解释为什么匿名函数确实有一个 .prototype
  • Object.getPrototypeOf(() =&gt; {}) === Function.prototype 注意这是真的。
  • 是的,他们似乎(根据 ES6 wiki)缺少 .prototype 字段,他们实际上有一个 __proto__。我真的不太喜欢用 javascript 来解释它为什么会发生,只是通过实验弄明白了,真的
  • @jcl—箭头函数不是构造函数,因此它们不需要公共原型属性。但由于它们是函数,它们内部的[[Prototype]]Function.prototype 并且可以为它们分配公共 prototype 属性。因此,虽然通过查找公共原型来检查箭头函数可能在某些甚至大部分时间都有效,但并不能保证。这一切都在规范中,只是需要一些时间来涉足它......
猜你喜欢
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2020-05-07
  • 2019-07-10
相关资源
最近更新 更多