如何区分箭头函数、类和普通函数? [英] How can I differentiate between an arrow function, class and a normal function?
问题描述
如何使用 ES6 中的引用来区分这三件事?
How can I differentiate between these three things in ES6 using its reference?
let x = i => i+1;
class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} }
function z(i) { return i+1; }
示例:
test(x) //=> 'arrow'
test(y) //=> 'class'
test(z) //=> 'function'
我如何区分转译器中的这些东西 - Traceur/Babel?
And how can I differentiate between these things in transpilers - Traceur / Babel?
推荐答案
我如何区分 ES6 中的这些东西?
How can I differentiate between these things in ES6?
- 箭头函数是不能用作构造函数的函数,并且没有
.prototype
属性.但是,方法也不是.它们继承自Function.prototype
. - 类是在没有
new
的情况下无法调用的函数,并且具有通常不为空的.prototype
对象.如果使用了extends
关键字,它们不会从Function.prototype
继承. - 函数是可以以任何一种方式调用的函数,并且确实具有 通常为空的
.prototype
.它们继承自Function.prototype
. - 生成器函数是具有
.prototype
的函数,它继承自内在的 GeneratorPrototype 对象,并且它们继承自内在的 Generator 对象. - arrow functions are functions that cannot be used as constructors, and don't have a
.prototype
property. However, methods don't either. They inherit fromFunction.prototype
. - classes are functions that can't be called without
new
, and that have a.prototype
object which is normally not empty. If theextends
keyword was used, they don't inherit fromFunction.prototype
. - functions are functions that can be called either way, and do have a
.prototype
that is normally empty. They inherit fromFunction.prototype
. - generator functions are functions that do have a
.prototype
which inherits from the intrinsic GeneratorPrototype object, and they inherit from the intrinsic Generator object.
如您所见,有一些线索.然而,属性和继承总是会被弄乱,所以你不能真正信任它.一个函数是否是构造函数(可以用 new
调用)无法从外部确定,你必须调用它并查看它是否抛出 - 这也可以伪造.
As you can see, there are some clues. However, the properties and inheritance can always be messed with, so you cannot really trust it. Whether a function is a constructor (can be called with new
) cannot be determined from outside, you have to call it and see whether it throws - which could be faked as well.
所以你最好的选择可能是 Function.prototype.toString
,看看源代码是什么样的.如果您的 ES 实现支持这一点.
So your best bet might be Function.prototype.toString
, to see how the source looked like. If your ES implementation supports that.
我如何区分转译器中的这些东西?
And how can I differentiate between these things in transpilers?
我认为没有任何转译器实现无原型的箭头和方法.类构造函数是否在被调用时抛出取决于转译的松散程度,但这无论如何都不是区分的好方法.toString
也不能正常工作.
I don't think any transpiler implements prototype-less arrows and methods. Whether a class constructor throws upon being called depends on the looseness of the transpilation, but that's not a good way for distinction anyway.
toString
doesn't work either afaik.
这篇关于如何区分箭头函数、类和普通函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!