I'm working on some JS where functions are passed around by reference, and it's difficult to see which function is being called at times. It will be passed around through 7-8 functions each with a ton of parameters, so it's very time consuming to track back where it came from. I'm working on changing a bit of this, but the only way I've been able to figure out to see which function is actually being called it is to do something like this:
if (console && console.log && method.toSource) {
console.log(method.toSource());
}
This only works in FF but at least then I can search for the source of the called f开发者_如何学编程unction. Is there a better way?
install firefox
install firebug addon
click on the bug icon on the lower right
click on script tab
click enable
reload page
click on stack tab on right panel in firebug
Have you tried console.trace()
in Firebug?
Try this
var whee = {
test: function(ab) {
console.log(ab);
this.test2('Hello', 'World');
},
test2: function(a, b) {
console.log(a+' '+b);
}
};
function augment(obj, withFn) {
var name, fn;
for (name in obj) {
fn = obj[name];
if (typeof fn === 'function') {
obj[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
fn.apply(this, arguments);
}
})(name, fn);
}
}
}
augment(whee, function(name, fn) {
console.log("calling " + name);
});
whee.test('hi');
the function augment takes an obj as the first parameter and a function as the second. It loops through all the members of the object looking for functions. When it finds one it replaces it with a function that calls the passed in function and then the original function. I stole almost all of the code from this stackoverflow answer.
It doesn't seem to play nicely when you pass it the window object so hopefully your functions are not all declared in the window scope.
There is also this answer in which they try to override the Function.prototype.call function with their own. I couldn't get it to work in Firefox but maybe you will have better luck.
Functions can be compared by reference, so if you have a dictionary like in Alex Brown's answer:
var whee = {
test: function(ab) {
console.log(ab);
this.test2('Hello', 'World');
},
test2: function(a, b) {
console.log(a+' '+b);
}
};
then you can just compare your now-anonymous reference with each:
function whichFunc(func, funcDict) {
for (var funcname in funcDict) {
if (func == funcDict[funcname]) {
return funcname;
}
}
}
Pretty simple.
精彩评论