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?
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?