javascript - 如何将此传递给Javascript中的嵌套函数?
问题描述
我试图执行这样的事情:
class A {
functionA() {
setTimeout(function() {
console.log(this);
}, 1000)
}
}
const a = new A();
a.functionA();
但this
总是指窗口对象。我知道你可以设置类似的东西var a = this
,但是有没有更优雅的方法可以将它从对象传递到内部函数?
解决方案
您可以使用箭头函数而不是常规函数来保留this
上下文:
class A {
functionA() {
setTimeout(() => {
console.log(this);
}, 1000)
}
}
const a = new A();
a.functionA();
另一种方法是.bind(this)
创建一个有界this
上下文的函数:
class A {
functionA() {
setTimeout((function() {
console.log(this);
}).bind(this), 1000)
}
}
const a = new A();
a.functionA();
推荐阅读
- c# - 捕获 Application.ExitThread 的事件
- javascript - Flask/没有 JS:可以在没有 javascript 的情况下制作动态下拉表单应用程序吗?(仅 python 和 HTML)
- javascript - 在使用 Angular cli 服务脚本时运行 webpack 开发服务器
- vba - 多次运行 VBA 代码
- angularjs - 有没有办法在ui路由器中传递状态的“数据”属性?
- python - 如何只调用numpy数组的内容?
- c++ - 如何在 C++ 中实现一个 avl 树,每个节点都是另一个 avl 树
- c++ - return 语句中的“表达式不能用作函数”
- javascript - 在 dijit 布局 tabcontainer 的一系列选项卡中更改一个选项卡的标签颜色
- excel - 如何使用 Microsoft Excel 2016 导入 CSV 文件?