Reputation: 345
I'm trying to find my way into learning Javascript and am running into an issue where several pieces of code that I'm told were identical, have different outcomes. I have found there are three ways of defining an object (instance):
version 1:
var obj = { //create the instance
variable: value
};
obj.fun = function() {
obj.variable += 1;
console.log('obj.fun is called');
};
version 2:
var obj = { //create the instance
variable: value,
fun: function() {
this.variable += 1;
console.log('obj.fun is called');
}
};
version 3:
function Obj() { //create the class
this.variable = value;
this.fun = function() {
this.variable += 1;
console.log('obj.fun is called');
}
};
obj = new Obj(); //create the instance
In fact what I am trying to do is creating a mouse event handler in a HTML5 canvas using this:
canvas_id.addEventListener("mousedown", obj.fun, false);
Currently, only version 1 is working if I try to call the function obj.fun
using this event listener, but I prefer to use version 2 because I think it's cleaner. In versions 2 and 3, the function is executed when calling obj.fun(newvalue)
(the console message is created), but the variable isn't changed to the new value; if I try to retrieve obj.variable
the original value is returned.
I'd like to know what's the exact difference between these three versions of writing, so I can understand what to use when. Thanks in advance.
Upvotes: 2
Views: 358
Reputation: 382454
What you have in the first version is a named variable obj
keeping the desired object. In the two other ones, this
(the context of the call) isn't your object (a common problem with event handling callbacks).
You can still use those versions by changing the binding to
canvas_id.addEventListener("mousedown", obj.fun.bind(obj), false);
or (to be compatible with IE8)
canvas_id.addEventListener("mousedown", function(){ obj.fun() }, false);
Upvotes: 3