Hi, I've got the following (trivial) example, and I'm not quite sure
how to get it to behave as I would like. When I click on the H1
element, I want the "testa" method to be called, and for it to update
number. But instead, "this" refers to the mousedown event...and the
function does not update the number.
Firstly, the value of a function's this keyword is set by the calling
function when the function is called. It is not set by the function
declaration or expression.
Where does "number" belong? Should it be a property of blah? If so,
make it a property of blah and use it.
How can I refer to "number" within the "testa" method?
To to that you need to create a closure that will be to a specific
instance of the testa execution object.
blah = {};
blah.test = function() {
this.number = 1;
The this keyword (most probably) refers to the object that the
function was called as a method of, or the window object. Since you
don't show how the function is called, we have to guess as you can set
to any object using various means, including using the Function
object's call() and apply() methods.
If you've called the function using blah.test(), then the this keyword
is a reference to the blah object. this.number=1 will result in a
number property being added to blah (if it doesn't already exist) and
its value set to 1.
var headerone = document.getElementById("h1");
utils.addEvent( headerone, 'click', this.testa );
You don't show the addEvent function, it may have an effect on what
the value of the this keyword is set to. Assuming the Mozilla event
model, the element with id=h1 now has an onclick handler whose value
is a reference to the annonymous function referenced by blah.testa.
When the function fires, the function is called and its this keywords
is set as a reference to the DOM element that fired the event and the
first parameter is set as a reference to the event object.
Now you see the value of blah.number, which is 1.
blah.testa = function( params ) {
alert( params );
params is a reference to the event object.
this.number++;
alert(this.number);
the event object doesn't have a number property, so you get
'undefined'. I expected this.number++ to throw an error but it
doesn't. One for Richard Cornford if he's lurking.
If you explain what properties number is required to have, a strategy
can be suggested. If you want each onclick to have its own instance
of number, you'll need to use a closure, then pass a reference to your
addEvent function so it can ensure it is passed to the testa function,
e.g. (using closures for both number and testa):
blah.test = function() {
var number = 1;
var fn = this.testa;
var headerone = document.getElementById("h1");
utils.addEvent( headerone, 'click', function(){
fn(number);
});
}
blah.testa = function( number ) {
number++;
alert(number); // shows 2 when h1 clicked on
}
If you need a reference to the event object, that can be
accommodated. If number should be a property of blah, do that.