2017-07-21 50 views
2

我想聲明一個JavaScript對象,像這樣:使用「這個」對象在JavaScript

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

我做了一些調試,發現裏面this.btn1this對象不再指Calculator對象。如何將textbox轉換爲Calculatortextbox

非常感謝提前!

回答

2

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

的老把戲我喜歡'that'更多。 –

+0

據我所知,使用'this'的問題在ES6中通過箭頭函數解決('()=> {...}') –

+0

非常感謝您的快速響應!我的代碼現在可用!定時器冷卻時,我會接受你的答案。 –