【发布时间】:2017-03-04 10:03:29
【问题描述】:
我想知道是否有办法区分 JavaScript 脚本函数 (function(){}) 和 JavaScript 本机函数(如 Math.cos)。
我已经知道func.toString().indexOf('[native code]') != -1 技巧,但我想知道是否有其他方法可以检测到它。
上下文:
我需要创建一个 No-op 转发 ES6 代理,它可以处理对象上的本机函数,但它以 TypeError: Illegal invocation 失败(请参阅 Illegal invocation error using ES6 Proxy and node.js)。
要解决这个问题,我 .bind() 我的代理的 get 处理程序中的所有函数,但如果我能有效地检测到本机函数,我只需要 .bind() 这些本机函数。
更多详情:https://github.com/FranckFreiburger/module-invalidate/blob/master/index.js#L106
注意:
(function() {}).toString() -> "function () {}"
(function() {}).prototype -> {}
(require('os').cpus).toString() -> "function getCPUs() { [native code] }"
(require('os').cpus).prototype -> getCPUs {}
(Math.cos).toString() -> "function cos() { [native code] }"
(Math.cos).prototype -> undefined
(Promise.resolve().then).toString() -> "function then() { [native code] }"
(Promise.resolve().then).prototype -> undefined
编辑:
目前,最好的解决方案是测试!('prototype' in fun),但它不适用于require('os').cpus ...
【问题讨论】:
-
你为什么要另一种方式?
-
@Tareq,detect-native-function 使用类似于
func.toString().indexOf('[native code]') != -1的fnToString和regexp -
@jonrsharpe,我需要创建一个 No-op 转发 ES6 代理,它可以处理对象上的本机函数,但这会失败(请参阅stackoverflow.com/questions/42496414/…)。
-
在问题中包含该上下文会有所帮助,因此人们不会建议具有类似限制的其他方法。
标签: javascript node.js function native