2011-11-21 11 views
8

llamando Tengo una función en JS que está recibiendo llamadas desde múltiples lugares ..Javascript encontrar la función

Ahora estoy probando esta página en un iPad y por lo tanto encontrar depurar un poco difícil.

¿Puedo averiguar de alguna manera (imprimir en la consola) desde donde se llama mi función?

+2

Esto ayudará a: http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript – Sid

+0

Un enlace más http://stackoverflow.com/questions/147891/javascript-exception-stack-trace –

Respuesta

13

¿Te gusta?

function testOne() { 
    console.log("Test 1"); 
    logTest(); 
} 
function testTwo() { 
    console.log("Test 2"); 
    logTest(); 
} 
function logTest() { 
    console.log("Being called from " + arguments.callee.caller.toString()); 
} 

testOne(); 
testTwo(); 

Si utiliza 'use strict'; en su archivo JavaScript, es necesario comentar/quitarlo, porque de lo contrario obtendrá algo como esto:

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

+3

Me estoy equivocando o .... Resultado de la expresión arguments.callee.caller no es un objeto – testndtv

+0

Estoy comprobando esto en iPad Safari ... si eso hace alguna diferencia ... – testndtv

+0

@James, +1, Tu función me ahorró tiempo para entender el marco existente y completar mi trabajo. ¡¡¡Muchas gracias!!! –

9

Una forma sencilla me gusta usar es arguments.callee.caller.name .

Diga lo que quería saber lo que se llama una función llamada myFunction:

function myFunction() { 
    console.log(arguments.callee.caller.name); 
    /* Other stuff... */ 
} 

El soporte de los navegadores para que esto no es tan grande, sin embargo, lo que podría utilizar arguments.callee.caller.toString() en lugar. Tenga en cuenta que esto le devolverá el contenido de la función que llamó a myFunction, por lo que tendrá que extraer el nombre de la función de usted mismo.

O, usted podría utilizar una buena función de seguimiento de la pila siguiente manera:

function getStack(){ 
    fnRE = /function\s*([\w\-$]+)?\s*\(/i; 
    var caller = arguments.callee.caller; 
    var stack = "Stack = "; 
    var fn; 
    while (caller){ 
     fn = fnRE.test(caller.toString()) ? RegExp.$1 || "{?}" : "{?}"; 
     stack += "-->"+fn; 
     caller = caller.arguments.callee.caller; 
    }; 
    return stack; 
} 

Seguimiento de la pila a través de http://www.amirharel.com/2010/01/25/using-caller-and-callee-for-stack-trace/

0

desea detallar acerca de llamadas Función:

function nishant(){ // Caller function 
    kumar(); 
}nishant(); 

function kumar(){ // Callee 
console.log("This functiona is being called by " + arguments.callee.caller.toString()); 
} 

En lugar de arguments.callee.caller.toString() también podemos usar functionName.caller

Ejemplo:

function nishant(){ // Caller function 
    kumar(); 
}nishant(); 

function kumar(){ // Callee 
console.log("This functiona is being called by " + kumar.caller); 
} 

de salida: será igual en ambos el caso anterior

This functiona is being called by function nishant() 
{ 
kumar(); 
} 
+0

* functionName.caller * es agradable, pero [no estándar] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller) (según MDN) – mTorres

Cuestiones relacionadas