Get calling object from double function

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Get calling object from double function

Post by Darkzaelus »

Hiya, if I have selected an element, added my own object to it as an attribute, and am trying to call a function from the object, how can I get the original calling element from the function?

Code: Select all

var obj._style.capture();
I'd love to know if this is possible.

Cheers,

Darkzaelus
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Get calling object from double function

Post by kaszu »

You can't without additional variable/argument or without changing scope.
Here is how:

Code: Select all

/* ------------ Initial code ----------- */
 
var div = document.getElementById('sample');
div.my_object = {
    sample_func: function () {
        alert(this);
        //this refers to my_object, which is not what we want
    }
};
div.my_object.sample_func();
 
/* ------------ Sample #1 ----------- */
 
div.my_object = {
    sample_func: function () {
        alert(this);
        //this now refers to DIV, but you can't access my_object anymore
    }
}
div.my_object.sample_func.call(div);
 
/* ------------ Sample #2 <- correct way how to do it in my opinion ----------- */
 
div.my_object = {
    htmlNode: div, //Reference to DIV
    sample_func: function () {
        alert(this.htmlNode);
        //this.htmlNode refers to DIV
    }
};
div.my_object.sample_func();
 
/* ------------ Sample #3 ----------- */
 
div.my_object = {
    sample_func: function (div) {
        alert(div);
        //div refers to DIV
    }
};
div.my_object.sample_func(div);
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: Get calling object from double function

Post by Darkzaelus »

Thanks for the reply! It works a charm (I used sample 2). I was originally referring to an external class, but now I have them referenced in the actual addition code.

Cheers!

Darkzaelus
Post Reply