我正在看看是否可以编写一些面向对象的 JavaScript,并且我有以下代码。
当我将 jquery 事件处理程序移动到构造函数中时,我感到很困惑,因为现在我有两个 this 变量...
我是否错误地处理了这个问题,或者有没有办法让它发挥作用?
function Dropdown(ddlname) {
this.Value = 0;
this.Selected = false;
this.DDL = ddlname;
this.Limited = false;
this.SelectLast = function () {
$(this.DDL + ' option:last').attr('selected', 'selected');
}
$(ddlname).change(function () {
var v = $(this).val(); // <== ?
if (typeof v == 'number') {
this.Value = v; // <== ?
this.Selected = true; // <== ?
}
});
return true;
};
最佳答案
您需要将构造函数上下文中的“this”分配给局部变量,以便能够在 jquery 事件处理程序中引用它。
function Dropdown(ddlname) {
this.Value = 0;
this.Selected = false;
this.DDL = ddlname;
this.Limited = false;
var hold = this;
this.SelectLast = function () {
$(hold.DDL + ' option:last').attr('selected', 'selected');
}
$(ddlname).change(function () {
var v = $(this).val(); // <== ?
if (typeof v == 'number') {
hold.Value = v; // <== ?
hold.Selected = true; // <== ?
}
});
return true;
};
关于javascript - 我可以将 jquery 处理程序放入构造函数中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6702555/