我正在尝试声明一个JavaScript对象,如下所示:
var Calculator = function() {
this.textbox = new Textbox({
...
});
this.btn1 = new Button ({
...
onClick: function() {
this.textbox.value += "1";
});
...
};
我做了一些调试,发现this.btn1
里面的this
对象不再引用Calculator
对象。如何textbox
参考Calculator
的textbox
?
提前非常感谢!
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";
});
...
};