gextra
gextra

Reputation: 8885

How to identify a a javascript prototype method callee's name from another prototype method

Having two javascript "object classes" MyClass1 and MyClass2 where a method (foo) in MyClass1 calls a method (moo) in MyClass2, I need to identify dynamically who is calling the function prototype moo from moo itself.

When I use the popularly suggested arguments.callee.caller accessors, I cannot derive the name. Overall I need to know from the method moo that it was was called from MyClass1's moo method, or others.

function MyClass1() {
    this.myAttribute1 = 123;
}

MyClass1.prototype.foo = function () {
     var myclass2 = new MyClass2();
     myclass2.moo();
};


function MyClass2() {
    this.mySomething = 123;
}

MyClass2.prototype.moo = function () {
     console.log("arguments.callee.caller.name = " +
         arguments.callee.caller.name);
     console.log("arguments.callee.caller.toString() = " +
         arguments.callee.caller.toString());
};

In the above example the results of arguments.callee.caller.name are empty, while the caller's toString() method shows the function's body but not its owner class or name of the method.

The reason for this need is that I want to create a debug method that traces the calls from method to method. I extensively use Object classes and methods.

Upvotes: 2

Views: 848

Answers (1)

Aadit M Shah
Aadit M Shah

Reputation: 74204

You need to name your function expressions. Try this:

function MyClass1() {
    this.myAttribute1 = 123;
}

MyClass1.prototype.foo = function foo() { // I named the function foo
     var myclass2 = new MyClass2;
     myclass2.moo();
};

function MyClass2() {
    this.mySomething = 123;
}

MyClass2.prototype.moo = function moo() { // I named the function moo
     console.log("arguments.callee.caller.name = " +
         arguments.callee.caller.name);
     console.log("arguments.callee.caller.toString() = " +
         arguments.callee.caller.toString());
};

See the demo: http://jsfiddle.net/QhNJ6/

The problem is that you're assigning a function which has no name to MyClass1.prototype.foo. Hence it's name property is an empty string (""). You need to name your function expressions and not just your properties.


If you want to identify whether arguments.callee.caller is from MyClass1 then you would need to do this:

var caller = arguments.callee.caller;

if (caller === MyClass1.prototype[caller.name]) {
    // caller belongs to MyClass1
} else {
    // caller doesn't belong to MyClass1
}

Note however that this method depends upon the name of the function being the same as the property name defined on MyClass1.prototype. If you assign a function named bar to MyClass1.prototype.foo then this method won't work.

Upvotes: 3

Related Questions