简体   繁体   English

当在JavaScript中执行传入的回调函数时,是否可以确定是否可以调用某个函数?

[英]Is it possible to determine whether a certain function may be called when a passed-in callback function is executed in JavaScript?

The question title basically says it all. 问题标题基本上说明了一切。 I made this Fiddle to make it easy to test. 我做了这个小提琴,以使其易于测试。 Here's the code: 这是代码:

var test = function(callback) {
    console.log("callback() might call alert()");
    callback();
}

test(function() {
    alert("one");
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM