[英]Is it possible to determine whether a certain function may be called when a passed-in callback function is executed in JavaScript?
Converting a function to a string returns the source code, you can search that with a regular expression. 将函数转换为字符串会返回源代码,您可以使用正则表达式进行搜索。
var test = function(callback) {
if (callback.toString().test(/\balert\s*\(/) {
console.log("callback might call alert()");
callback();
};
This isn't perfect, though. 不过,这并不完美。 It won't work with:
它不适用于:
var foo = alert;
test(function() {
foo("Fooled you!");
});
It could also get a false positive if alert(
appears in a string. 如果
alert(
出现在字符串中,也可能会产生误报。
You can redefine function alert 您可以重新定义功能警报
function alert(str) { console.log('Somebody call alert:'+str); }
But IMHO it can't be definitely checked before call. 但是恕我直言,在致电之前无法确定是否对其进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.