在 ECMAScript 6 中typeof
根据规范,类的数量是'function'
.
但是,根据规范,您也不允许将通过类语法创建的对象作为普通函数调用来调用。换句话说,您必须使用new
关键字,否则会抛出 TypeError。
TypeError: Classes can’t be function-called
因此,如果不使用 try catch(这会非常难看并且会破坏性能),您如何检查函数是否来自class
语法或来自function
syntax?
我认为检查函数是否为 ES6 类的最简单方法是检查结果.toString() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/toString方法。根据es2015规范 https://people.mozilla.org/%7Ejorendorff/es6-draft.html#sec-function.prototype.tostring:
字符串表示形式必须具有 FunctionDeclaration FunctionExpression、GeneratorDeclaration、GeneratorExpression、类声明 https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-class-definitions, 类表达式 https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#prod-ClassExpression、ArrowFunction、MethodDefinition 或 GeneratorMethod,具体取决于对象的实际特性
所以检查函数看起来很简单:
function isClass(func) {
return typeof func === 'function'
&& /^class\s/.test(Function.prototype.toString.call(func));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)