[英]Is there a way to look inside a (anonymous) function?
In JavaScript, let's say you have: 在JavaScript中,假设你有:
function doSomething(callback) {
if (callback instanceof Function) callback();
}
doSomething(function() {
alert('hello world');
});
Is there a way to check what is inside 'callback' (like, the fact that alert()
is called) from doSomething()
? 有没有办法从doSomething()
检查内部'回调'内部(例如,调用alert()
的事实doSomething()
? Something like: 就像是:
function doSomething(callback) {
alert(callback.innards().indexOf('alert('));
}
I'm just curious 我只是好奇
Function.prototype.toString() gives an implementation-dependent representation of the function
. Function.prototype.toString()给出了函数 implementation-dependent representation of the function
于implementation-dependent representation of the function
。 However built-in functions will return something like: 但是内置函数将返回如下内容:
function Array() {
/* [native code] */
}
and host methods can return anything, even throw an error. 和宿主方法可以返回任何东西,甚至抛出错误。 So the strict answer is yes, maybe. 所以严格的答案是肯定的,也许吧。 But in a practical sense, it is not reliable. 但从实际意义上讲,它并不可靠。
Some browsers support toString() on functions. 有些浏览器在函数上支持toString() 。
function doSomething(callback) {
console.log( callback.toString().indexOf('alert(') )
if (callback instanceof Function) callback();
}
You should be able to say: 你应该可以说:
alert( callback.toString().indexOf('alert(') );
However that won't distinguish between the beginning of a function alert(
, the beginning of a function myspecialalert(
, and the text "alert("
if it happens to be in a string literal - so you may need to do a bit of parsing. 但是,这不会区分函数alert(
的开头(函数myspecialalert(
的开头myspecialalert(
和文本"alert("
如果碰巧是在字符串文字中 - 所以你可能需要做一些解析。
Not sure how cross-browser this is, but in Firefox at least .toString()
returns the whole text of the function including the word "function" and the parameter list. 不确定跨浏览器是怎么回事,但在Firefox中至少.toString()
返回函数的全文,包括单词“function”和参数列表。
callback.toString().indexOf('alert(');
或者做正则表达式匹配,如:
/alert *\(/.test(callback.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.