簡體   English   中英

如何在事件中將變量傳遞給構造函數方法?

[英]How to pass variable to constructor methods in events?

在一個原型方法中,我有以下代碼:

DragDrop.prototype.startDrag = function() {
// ... other code
  this.mouseMove = this.drag.bind(this);
  ...

.bind就是這樣,我可以從我調用的函數( this.drag )中引用該對象。

(該事件不能是匿名函數,因為我需要稍后將其刪除,否則我將一直拖動下去...)

...
window.addEventListener('mousemove', this.mouseMove, false);
}

這就是我正在使用的上述功能。 在Safari和Chrome中一切正常,但在Firefox事件中未定義。

DragDrop.prototype.drag = function() {
    console.log(event);
}

如何解決?

附帶說明一下,我是構造函數的新手,很高興知道是否還有另一種方法可以做到這一點/無需綁定。 在理想的世界中,我也想將更多變量傳遞給.drag函數。

在某些實現中,由於遺留原因, event是全局變量(由IE啟動的不良做法)。 它實際上應該是事件處理程序的參數:

DragDrop.prototype.drag = function(event) {
//                                 ^^^^^
    console.log(event);
}

請注意,這與bind函數無關,事件處理程序也無法解除綁定。

暫無
暫無

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

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