javascript - JS/TS必须使用bind但仍需要原来的this

标签 javascript angular typescript closures bind

我不知道如何解决我遇到的这个用户交互问题。 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/

相关文章:

node.js - 如何将 TypeScript 中的 ExpressJS 部署到 Azure?

reactjs - 提交后重置 React-Select (Unform)

javascript - 具有主值和次值的数组排序

javascript - 创建 html 表单将下载链接发送到给定的电子邮件地址?

javascript - Sails.js:重定向后检索 URL 参数

angular - material-component-datetime-picker-您提供了 'undefined' 预期的流。你可以提供一个 Observable、Promise、Array 或 Iterable

javascript - CanActivate,动态 url 解析器(多个嵌套动态段)

javascript - Highcharts 多 y 轴最小-最大问题

node.js - Visual Studio代码: "' tslib' cannot be found"error in Angular project

javascript - 如何在包含 <br> 作为换行符的段落中的多行上显示字符串值