在 JavaScript 中使用"this"对象



我正在尝试声明一个JavaScript对象,如下所示:

var Calculator = function() {
this.textbox = new Textbox({
...
});
this.btn1 = new Button ({
...
onClick: function() {
this.textbox.value += "1";
});
...
};

我做了一些调试,发现this.btn1里面的this对象不再引用Calculator对象。如何textbox参考Calculatortextbox

提前非常感谢!

var self = this的老把戏

var Calculator = function() {
var self = this;  // self is a reference to calculator, always.
this.textbox = new Textbox({
...
});
this.btn1 = new Button ({
...
onClick: function() {
self.textbox.value += "1";
});
...
};

最新更新