我想将我的类的实例传递给绑定(bind)的 d3 拖动函数。
我尝试将其分配给一个变量并传递它。 我最终得到了未定义。
我有点困惑?在这种情况下我将如何访问我的类的实例?
谢谢。
class foo {
constructor(a){
this.a = a;
}
method1(){
var referenceToMyClass = this;
this.dragEvent = d3.drag(referenceToMyClass)
.on("drag", this.method2);
d3.select('target id').call(this.dragEvent);
}
method2(){
//Here i want to access referenceToMyClass;
//referenceToMyClass is undefined.
//this refers to the event target.
}
}
最佳答案
您可以将其设为一个函数,并将其传递到您将有权访问 this
的函数中:
class foo {
constructor(a){
this.a = a;
}
method1(){
var referenceToMyClass = this;
var method2 = function(){
//do something with referenceToMyClass
}
this.dragEvent = d3.drag(referenceToMyClass)
.on("drag", method2);
d3.select('target id').call(this.dragEvent);
}
}
或者您可以使用绑定(bind):
class foo {
constructor(a){
this.a = a;
this.method2.bind(this);
}
method1(){
var referenceToMyClass = this;
this.dragEvent = d3.drag(referenceToMyClass)
.on("drag", this.method2);
d3.select('target id').call(this.dragEvent);
}
method2(){
//this refers to the object now.
}
}
关于javascript - 在类中绑定(bind) d3 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619102/