marifrahman
marifrahman

Reputation: 690

How can I get the caller reference inside another object's called function?

Following is the code I am trying :

var varincaller;
function mainfunction(arg)
{
 varincaller = arg;
}

function mainfunction2()
{
var obj2 = new anotherclass;

obj2.anotherfunction = function()
{
   //How can I get varincaller, here ?
}
}

Can anybody please help ?

Upvotes: 0

Views: 60

Answers (2)

David G
David G

Reputation: 96810

Given your code, since varincaller is defined outside or in the same scope in which .anotherfunction is defined, we can access it directly:

obj2.anotherfunction = function() {
   varincaller; // this works
};

Upvotes: 1

Alex
Alex

Reputation: 35409

The following statement creates a global variable varincaller. So, it's accessible from any function.

var varincaller;

This statement isn't syntactically sound:

var obj2 = new anotherclass;

Should be:

var obj2 = new anotherClass();

To access varincaller inside the function in question it is a simple call to it:

obj2.anotherfunction = function()
{
   alert(varincaller);
}
obj2.anotherfunction();

Upvotes: 1

Related Questions