Sarath
Sarath

Reputation: 9146

How do you find out the caller Object in JavaScript

I have

 var X={
     method1 : function(){
                A();
              },
     method2 : function(){
                A();
              },
    
    }

function A(){
       console.log('im from methodNAME of ObjNAME ');
}

How can I find out the name of the method and Object that the function is called from?

Upvotes: 2

Views: 8604

Answers (3)

resti
resti

Reputation: 45

You can use console.log(new Error()) within the function and parse the list of stack trace.

Upvotes: 0

ZenMaster
ZenMaster

Reputation: 12742

The way you defined and called your A function the object that A is called for will be DOMWindow object - that is, the global object.

As for from which method of X it is called (which is what you mean by methodNAME, I assume) - in the way you defined your methods (defining an anonymous function and assigning ir to a property) you won't be able to get the name.

Had you declared your X object like this:

var X = {
    method1: function method1() {
        A();
    },
    method2: function method2() {
        A();
    },

}

and your A function like this:

function A() {
    console.log(A.caller);
}

then calling:

X.method1();
X.method2();

would produce console output like this:

function method1() {
        A();
    }

function method2() {
        A();
    }

which you could then parse and retrieve the name of the calling method.

Or if you defined A like this:

function A() {
    console.log(A.caller.prototype);
}

then the output on would show:

method1
method2

where method1 and method2 are prototype objects - so you'd have to perform some manipulations as well.

EDIT: fixed bad copy/paste = A.caller.prototype -> A.caller.

Upvotes: -1

Ariel
Ariel

Reputation: 26753

You can use arguments.caller but it's not reliable: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/caller

It has been replaced with https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/caller which seems to have reasonable browser support.

Upvotes: 5

Related Questions