如何查找函数是内置函数还是用户定义函数

时间:2013-10-26 17:26:52

标签: javascript

让我们说如果我有一个功能a。我想知道它的内置功能还是用户定义的功能。
我已经尝试检查a.toString()中是否有[native code],但是具有子串[native code]的用户定义函数会失败。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

一种可能是天真的方法是测试函数名称是否存在文档的属性:

function newFunction (){
    return true;
}

console.log('newFunction' in document, 'toString' in document);

当然,这是进行详尽测试,如果将该函数创建为prototype的扩展名,则会失败,例如:

function newFunction (){
    return true;
}

Object.prototype.newFunctionName = function () {
    return 10 * 2;
};

console.log('newFunction' in document, 'toString' in document, 'newFunctionName' in document); // false, true, true

JS Fiddle demo

鉴于它'eval' in document也失败了(因为它返回false),那么这将<或> 可以,只能识别对象的原型方法。这至多是一个不完整的解决方案。

答案 1 :(得分:1)

所以,这里要检查一些代码:

var rgx = /\[native code\]\s*\}\s*$/;

function some(){
    '[native code]'
}

console.log(
    rgx.test(print.toString()),
    rgx.test(some.toString())
);