Let's see a couple of issues:
- The
alertx()
doesn't receive an event
argument.
- In that function you are calling
getMouseXY
using this
. The this keywords at that moment, will refer to the element that triggered the event.
- You are binding the event handler to an unknown
object
variable.
I think you want to do something like this:
function getMouseXY(event){
var x = event.clientX - this.offsetLeft, // notice, 'this' is used
y = event.clientY - this.offsetTop;
return [x,y];
}
function alertx(event){
var c = getMouseXY.call(this, event); // set the element as 'this'
alert(c[0]);
}
And if you have a constructor function, and the above functions are instance methods, you can do something like this:
function MyObject () { // constructor
}
MyObject.prototype.getMouseXY = function (event) {
var x = event.clientX - this.offsetLeft,
y = event.clientY - this.offsetTop;
return [x,y];
};
MyObject.prototype.alertx = function (event, element) {
var c = this.getMouseXY.call(element, event);
alert(c[0]);
}
When binding the event, you can add an anonymous function, to enforce the context:
var object = new MyObject();
document.getElementById('cbackground').addEventListener('mouseup', function (e) {
object.alertx(e, this); // alertx will be called with the correct 'this'
}, false);
Edit: In response to your comment, you just have to know how the context (the this
keyword) is set implicitly:
When you call a instance method like:
obj.method();
The this
keyword inside the method
, will refer to obj
.
The same thing happens when you call global variables, since they are members of the global object (window
in browser scripting):
globalFunction();
Is equivalent to:
window.globalFunction();
And the context inside that function will be the global object itself (window
).
Another case happens when you use the new
operator:
var instance = new MyConstructor();
The this
keyword in that case will be a new object, created by the use of the new
operator.
When you use a function as an event handler, the this
keyword will refer to the element tha triggered the event:
document.getElementById('myId').onclick = obj.myFunction;
In that case myFunction
is a instance method of obj
, but the this
keyword will refer to the DOM element that has been clicked.
And finally, as you saw in my code, the context can be set explicitly by the use of call
or apply
.