我不知道如何解决我遇到的这个用户交互问题。 API是3DMol
我正在尝试访问
中的两个this
元素
model.setClickable({chain: theChain, resi: mappedPosition}, true, function(){
console.log(this);
});
首先,对于上面的原始实现,this
将是用户单击的位置。但是,我还需要将单击的位置与外部调用对象的一些值结合起来。
我尝试了 .bind(null,this)
但在函数中 this
设置为 null
。
我尝试了关闭
const clickClosure = function(){
const mutations = self.alignment.mutations;
function clicker(){
console.log(this);
console.log(mutations);
}
return clicker();
}
model.setClickable({chain: theChain, resi: mappedPosition}, true,clickClosure);
发现突变存在,但this
未定义。知道如何在不使用全局变量的情况下获得两者吗?
最佳答案
使用 lambda 函数传递词法 this
。
model.setClickable({chain: theChain, resi: mappedPosition}, true, (stuff) => {
console.log(this, stuff); // no `this` binding to the function
});
这应该将 this
绑定(bind)到调用者,这实际上是从这样的回调中获取引用的唯一方法。
关于javascript - JS/TS必须使用bind但仍需要原来的this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902610/