在JavaScript中使用“this”对象

时间:2017-07-21 21:30:07

标签: javascript

我试图像这样声明一个JavaScript对象:

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

我做了一些调试,发现this内的this.btn1对象不再引用Calculator对象。如何将textbox引用到Calculator的{​​{1}}?

非常感谢提前!

1 个答案:

答案 0 :(得分:3)

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";
    });
    ...
};