2013-10-26 42 views
2

可以说如果我有一个功能a。我想知道它的内置功能或用户定义的功能。
我试过检查a.toString()是否有[native code],但是具有子字符串[native code]的用户定义函数会失败。有没有更好的方法来做到这一点?如何查找功能是否内置功能或用户定义

+2

_Custom_功能'的toString()'不能结束'[本地代码]}',否则函数(源)会因语法错误编译。 – tenbits

+0

哦,这是有道理..guess我应该有更多的想法 聚苯乙烯 - 我可以接受它,如果发布这是一个答案 – everconfusedGuy

回答

1

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

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

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

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

我已经使用过'some.toString()。indexOf('[native code]',some.toString()。length - '[native code]'。length)!== -1 '测试它..使用正则表达式好像也不错 – everconfusedGuy

+0

你的代码是否可以使用内置函数?当你查看字符串化函数的结尾时,但它以'[native code]}结尾'而且在IE中有新行'[native code]'和'}',所以正则表达式也可以处理它。祝你好运! – tenbits

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),那么这将或可以,只有合作,以确定对象的原型方法。充其量,这是一个不完整的解决方案。

+0

'eval'在文档中返回false – everconfusedGuy

+0

不幸的是,我很尴尬,承认我有没有更好的想法... :( –