簡體   English   中英

按事件寬度調用方法JS OOP(原型)

[英]Call Method By Event width JS OOP (prototype)

我希望有人能幫助我=)

我嘗試保持示例簡單:

function myClass(){
//some Code
}

myClass.prototype.func1 = function(){
//some Code
}

myClass.prototype.func2 = function(){
   document.getElementById("myEl").onclick = function(){
      this.func1 //does not work, this is only the Element...
   }
}

調用func1如何工作? 我想在func2中綁定onclick事件。

首先,您必須保留對當前對象的引用。 正如您已經注意到的,在事件處理程序內部, this是指DOM元素。 你可以這樣做

var self = this;

其次,您必須實際調用該函數:

self.func1();

完整的例子:

myClass.prototype.func2 = function(){
   var self = this;
   document.getElementById("myEl").onclick = function(){
      self.func1();
   };
}

在較新的瀏覽器中,您還可以使用.bind() [MDN]顯式定義this應引用的內容(有關其他瀏覽器的墊片,請參見MDN文檔):

document.getElementById("myEl").onclick = this.func1.bind(this);

onclick函數中, this值綁定到要單擊的元素。 您需要在func2內部保留this的副本(引用):

myClass.prototype.func2 = function(){
    var self = this; //keep a reference to the this value
    document.getElementById("myEl").onclick = function(){
        self.func1();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM