javascript 如何获取当前的函数对象引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4609328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get current Function object reference
提问by PleaseStand
itself.bind = function (object, method, callback, context, args, includeEventArgs) {
var handler, originalArgLen;
args = args.slice(0, arguments.length);
originalArgLen = args.length;
context = context || null;
handler = function () {
if (includeEventArgs) {
for (var i = arguments.length - 1; i >= 0; i--) {
args.push(arguments[i]);
}
}
callback.apply(context, args);
};
handler.userArgsLength = originalArgLength;
object[method] = handler;
};
Suppose I call
假设我打电话
TOOL.bind(canvas, "onmouseover", doDrawFunc, [currentDrawingTool], true);
I want to be able to access userArgsLengthfrom from within the doDrawFunc.
我希望能够userArgsLength从doDrawFunc.
回答by PleaseStand
You are looking for arguments.callee.caller.userArgsLength.
您正在寻找arguments.callee.caller.userArgsLength.
arguments.calleeis a reference todoDrawFunc..calleris the function that called it (handler)..userArgsLengthis the property of that function object.
arguments.callee是对 的引用doDrawFunc。.caller是调用它的函数 (handler)。.userArgsLength是该函数对象的属性。
Edit:I do not believe there is any way to avoid arguments.calleewithout changing your main function. You probably should be passing whatever the callback needs access as an argument to that callback function anyways. You could even pass in handleras an argument.
编辑:我不相信有任何方法可以避免arguments.callee不更改您的主要功能。无论如何,您可能应该将回调需要访问的任何内容作为参数传递给该回调函数。你甚至可以handler作为参数传入。
回答by Ryan McGrath
Move the assignment of handler.userArgsLength to an earlier point, shove it onto the apply array stack, and bam, you can assume it's the final argument.
将 handler.userArgsLength 的赋值移到更早的点,将其推入应用数组堆栈,然后,您可以假设它是最后一个参数。
Not sure why you'd wanna use arguments.callee anyway; from what I understand, traversing backwards like that can get really slow if you're not careful.
不知道你为什么要使用arguments.callee;据我所知,如果您不小心,像这样向后移动会变得非常缓慢。

