2

I am trying to declare a JavaScript object like so:

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

I did some debugging and found that the this object inside this.btn1 no longer refers to the Calculator object. How can I reference textbox to the Calculator's textbox?

Many thanks in advance!

Daniel Hong
  • 93
  • 1
  • 7

1 Answers1

3

The old trick of 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";
    });
    ...
};
corvid
  • 10,733
  • 11
  • 61
  • 130