Event handler scope weirdness

R

rsheridan6

Hi,

I'm writing a function to validate fields, and I'm confused about
variable scope. Here's what I have:

function RequiredField(name, error_message, error_display_id) {
this.name = name;
this.error_message = error_message || 'Required field';
this.error_display_id = error_display_id || name + '-message';

this.onblurrer = function () {

//this is the strange part

alert('this.check: ' + this.check + ' this.showErrorMessage: ' +
this.showErrorMessage);
this.check();
this.showErrorMessage();
return true;
};

$(this.name).onblur = this.onblurrer
}
RequiredField.prototype.check = function () {
alert('check: this.name: ' + this.name);
return !!$(this.name).value;
}
RequiredField.prototype.showErrorMessage = function () {
alert('show');
$(this.error_display_id).innerHTML = this.error_message;
}

Going into a javascript shell, I find that if I call an RequiredField
object's onblurrer directly, it does what I expected, but if I call
$(name).onblur() (with $ being prototype's shortcut for
getElementById), the alert box shows that this.check and
this.showErrorMessage are undefined, which is also what happens after
the real onblur event in the browser.

I'm pretty much stumped by this. I thought Javascript was lexically
scoped, which would mean that onblurrer shouldn't change just because
of who calls it. Are there exceptions to lexical scope?
 
R

rsheridan6

OK, I figured this out. 'this' is not a variable and it's provided by
the caller (IOW it's dynamically scoped) so the answer is to do
something like

function Foo() {
var that = this
....
onclick = function () {that.bar}
}

Too bad the word 'this' is effectively ungoogleable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top