Page 1 of 1
Get calling object from double function
Posted: Mon May 18, 2009 9:20 am
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?
I'd love to know if this is possible.
Cheers,
Darkzaelus
Re: Get calling object from double function
Posted: Mon May 18, 2009 12:10 pm
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);
Re: Get calling object from double function
Posted: Mon May 18, 2009 12:31 pm
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