Tutorial :JS: Is there a way to tell what object called a function?



Question:

In a function is there a way to get a reference to the object that called it? I have the same instance of a Flash object on the page twice, each one can make calls to JS through ExternalInterface, I cannot code the Flash objects to each pass a different ID because it is 2 instances of the same Flash object, so it there a way for JS to get a reference to which one called the function?

Thanks!


Solution:1

Can't you pass an ID to the Flash object when you instantiate it? (via a query string or params). Then you could use that ID in your JavaScript function calls.


Solution:2

I don't know about ExternalInterface but have you tried examine the this object during the execution of your function?

Of course you could always use a closure. Ultimately you have to give the Flash object a function to be executed. For example I have myObj1 and myObj2 that take a callback method fnCallback but for some reason does not set the this context when executing this functions to themselves. Hence I can do this:-

function setCallback(obj, fn)  {    obj.callback = function() {fn.apply(obj, arguments);}  }    setCallback(myObj1, fnCallback);  setCallback(myObj2, fnCallback);  

Now I can code fnCallback using this as a reference to the specific object that is calling the function.


Solution:3

arguments.caller or Function.caller but you might want to look at reorganizing your code to avoid using them. There really is another way to get what you want -- I guarantee it.

Edit: AnthonyWJones pointed out that you're actually looking for the this operator.

The this keyword refers to the context object (a.k.a. current object). In general, in a method, this refers to the calling object.


Solution:4

If you are looking for a way to find a non-function element that called a function, you might consider using the event. This is a pretty handy function I use a lot when passed an event object.

function getTargetElement(evt) {    evt = (evt) ? evt : ((window.event) ? window.event : "");    var elem;    if (evt.target) {        elem = (evt.target.nodeType == 3) ? evt.target.parentNode : evt.target;    } else {        elem = evt.srcElement;    }    return elem;  }  

So, for example, if you call a function "find(event);" from a clicked element, find can be coded to use this method to get the event object:

function find(evt){    var clickedObj = getTargetElement(evt);    alert(clickedObj.tagName); //alerts "TD"  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »