Reputation: 25346
I have a class that creates an anchor object. When the user clicks on the anchor I want it to run a function from the parent class.
function n()
{
var make = function()
{
...
var a = document.createElement('a');
a.innerHTML = 'Add';
//this next line does not work, it returns the error:
//"this.add_button is not a function"
a.onclick = function() { this.add_button(); }
...
}
var add_button = function()
{
...
}
}
How can I get this done?
Upvotes: 1
Views: 806
Reputation: 94193
The reason it's not working is that this
in the context of the onclick
function is not the same as this
in the context of the n
function/"class". If you want this
within the function to be equivalent to this
from the class, you need to bind this
to the function.
Binding is a way of changing the scope of a function -- essentially if you bind to a function, you are replacing the this
variable to point to something else. You can read more about binding in Javascript in this alternateidea article.
If you were using prototype, for example, you could do something like:
function n()
{
var make = function()
{
...
a.onclick = function() { this.add_button() }.bind(this);
...
}
}
Which would bind class n
's this
to the onclick function, thus giving the effect you want.
Upvotes: 1
Reputation: 3708
The "this" in "this.add_button();" is actually referring to the anchor element itself which has no "add_button()" function, if I'm not mistaken.
Perhaps this would work:
a.onclick = function() { n.add_button(); }
Upvotes: 0
Reputation: 12867
Looks like you just need to get rid of the "this." in front of add_button()
You are declaring add_button as a local variable (or private in the weird way that javascript classes work), so it isn't actually a member of "this".
Just use:
a.onclick = function(){add_button();}
Upvotes: 5