Reputation: 2166
I am trying to reference this.foo in an object I created, however this is referencing the HTML element that triggered the function. Is there any way that I can preserve the references to this in an object when it is called via an event?
Here is an example of what is going on:
$('document').on('click','button',object.action);
var object = {
foo : null,
action : function(){
this.foo = "something";
}
};
The error I would receive is
Uncaught TypeError: Object #<HTMLInputElement> has no variable 'var'
Upvotes: 0
Views: 319
Reputation: 38173
You can pass object
as the this
value using .apply():
$('document').on('click','button',function(){object.action.apply(object); });
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Your this
should be referencing object
but it is not most likely because of the use of var
which is a reserved word in JavaScript.
Upvotes: 0
Reputation: 2874
If you want to preserve this
, you should probably attach your event like that:
$('document').on('click','button',function() { object.action() });
Also, if you use this object as it is presented in the question, you may as well use object
instead of this
:
var object = {
foo : null,
action : function(){
object.foo = "something";
}
};
Also you might want to familiarize yourself with the Bind, Call, and Apply - jQuery uses these behind the scenes to replace your this
with HTML Element;
Also, var
is a reserved keyword and you should not use it for a property name; if you really want to do that, use a string "var"
and access it via []
notation like this:
var a = {"var": 1}
a['var']
Upvotes: 2
Reputation: 8163
Change this.var
to object.var
The problem that this
refers to context of where it was called from.
You call object.action
from click event on button, so this
is #<HTMLInputElement>
here.
And, as it was already said, don't use reserved words like var
as variable names
Upvotes: 0
Reputation: 186
var ist reserved word in JavaScript.
This works fine:
$(document).ready(function(){
var myObj = {
myVal: null,
action:function(){
this.myVal = "something";
}
};
myObj.action();
console.log(myObj.myVal);
});
Here link to JS Bin
I hope i could help.
Upvotes: 0