簡體   English   中英

在拖動事件的函數內訪問'this'

[英]Access 'this' inside a function on drag event

我有一個拖動事件的以下代碼:

BusinessProductFigure.prototype = new Figure();
BusinessProductFigure.prototype.constructor = BusinessProductFigure;
BusinessProductFigure.prototype.addTo = function(c, x0, y0, id) {
console.log("this=",this);
var n = d3.select(this);
var wasMoved = false;
var dragger = d3.behavior.drag()
    .origin(function(d){return d;})
    .on("drag", this.move)
    .on("dragend", dropHandler)

函數this.move在上面的代碼中執行並執行它的指定函數。 但是,我想添加一個在拖動事件上調用的函數。 我嘗試了以下方法:

BusinessProductFigure.prototype.addTo = function(c, x0, y0, id) {
console.log("this=",this);
var n = d3.select(this);
var wasMoved = false;
var dragger = d3.behavior.drag()
    .origin(function(d){return d;})
    .on("drag", function(){wasMoved=true; this.move})
    .on("dragend", dropHandler)

但上面的代碼並沒有調用move函數。 如何在函數內訪問“this”屬性?

您可以使用bind()綁定相關上下文,並使用parenthensis來調用該方法:

.on("drag", function(){wasMoved=true; this.move()}.bind(this))

另一種解決方案,因為2016年已經是使用箭頭函數來保留詞匯上下文:

.on("drag", () => {
   wasMoved = true;
   this.move()
})

暫無
暫無

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

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