2013-07-09 32 views
1

我試圖在類實例中設置HTMLElement成員的onclick事件處理程序,但這兩個嘗試都存在問題:將類中的HTMLElement成員的onclick屬性設置爲同一類的方法

1:關鍵字此不能用於

class ClassName { 
    div: HTMLElement; 
    constructor() { 
    this.div = document.createElement('div'); 
    this.div.onclick = function(e) { 
     this._onclick(); // keyword 'this' is not the instance in this scope 
    } 
    } 
    _onclick() { 
    alert('I've been clicked!'); 
    } 
} 

2:錯誤:無法將 '空隙' 至(EV:FocusEvent)方法。=>任何'

class ClassName { 
    div: HTMLElement; 
    constructor() { 
    this.div = document.createElement('div'); 
    this.div.onclick = this._onclick(); // error 
    } 
    _onclick() { 
    alert('I've been clicked!'); 
    } 
} 

我認爲這表明我對語言的理解不夠。如果有人可以請澄清,並可能發佈解決方案,將不勝感激!

+1

你的第二個例子也許應該''this.div.onclick = this._onclick;''(沒有括號)。 –

回答

4

使用箭頭符號具體到打字稿:中

class ClassName { 
    div: HTMLElement; 
    constructor() { 
    this.div = document.createElement('div'); 
    this.div.onclick = (e) => { 
     this._onclick(); // keyword 'this' is the instance in this scope 
    } 
    } 
    _onclick() { 
    alert('I've been clicked!'); 
    } 
} 

()=>代替function()自動轉義this你如以下打字稿:

class ClassName { 
    foo = "123"; 
    constructor(){ 
     var x =()=>{ 
      alert(this.foo); 
     } 
    } 
} 

基因費率以下JavaScript:

var ClassName = (function() { 
    function ClassName() { 
     var _this = this; 
     this.foo = "123"; 
     var x = function() { 
      alert(_this.foo); 
     }; 
    } 
    return ClassName; 
})(); 

通知var _this = this使用函數內閉合,其保持this_this.foo

3

this關鍵字綁定到調用函數的上下文。 當該函數由於DOM元素的事件(如onclick)而被調用時,它指向該元素。

用於您的第一個例子中的解決方法是保持在一個新的變量構造方面,它會調用that:加括號

class ClassName { 
    div: HTMLElement; 
    constructor() { 
    this.div = document.createElement('div'); 
    var that = this; //that and this both point to the new Object 
    this.div.onclick = function(e) { 
         //this now points elsewhere 
     that._onclick(); //that still point to the new object 
    } 
    } 
    _onclick() { 
    alert('I\'ve been clicked!'); 
    } 
} 

在你的第二個例子,你評估onclick功能,讓你將其結果分配給div.onclick屬性。

正確的代碼是:

class ClassName { 
    div: HTMLElement; 
    constructor() { 
    this.div = document.createElement('div'); 
    this.div.onclick = this._onclick; 
    } 
    _onclick() { 
    alert('I\'ve been clicked!'); 
    } 
} 
相關問題