javascript - Javascript this 上下文绑定
问题描述
我正在尝试了解绑定方法,并且编写了以下代码:
//
//Window Context
function Hello(d) {
//Always this reffers to calling context
console.log(d);
}
Hello("ABC");
function Student(sname) {
this.name_n = sname;
this.hello = Hello;
this.printAfter2Seconds = printAfter2Seconds.bind(this);
this.print = function() {
console.log(`Student Name: ${this.name_n}`);
}
}
printAfter2Seconds = function() {
console.log(`Before Set TimeOut - ${this.name_n}`);
//let that = this;
setTimeout(function() {
//console.log(this);
console.log(`After Set TimeOut - ${this.name_n}`);
},2000);
}
function Department(dname) {
this.name_n = dname;
this.hello = Hello;
this.printAfter2Seconds = printAfter2Seconds.bind(this);
}
let s = new Student("ABC");
s.hello(s.name_n);
s.printAfter2Seconds();
let d = new Department("IT");
d.hello(d.name);
d.printAfter2Seconds();
//
如果我评论 setTimeout 行和结束 setTimeout 的行,如下所示:
//setTimeout(function() {
//console.log(this);
console.log(`After Set TimeOut - ${this.name_n}`);
// },2000);
我得到了预期的输出 ABC 和 IT。但是,如果我包括 setTimeout,我两次都不确定。所以我猜测我需要再次调用 bind 的地方。这可能不是您每天都在尝试理解绑定的微不足道的示例。
所以我需要了解如何在 setTimeout 内绑定函数的 this 上下文,甚至是可能的。
提前致谢。
解决方案
推荐阅读
- java - 将文本添加到pdf?
- python - 如何在 Python 中打印到 .txt 文件的下一行
- java - Redisson JAR 执行:ClassNotFoundException:org.redisson.RedissonReference
- python - Opsgenie powershell 警报帖子不起作用
- python - 查询每组前 N 个元素的列表
- sql-server - 使用 AD 用户将 MuleSoft 连接到 SQL Server
- javascript - React Konva Transformer 错误“无法读取未定义的属性 'getStage'”
- c - 如何在 C 中专门使用汇编内联?
- python - 如何在不运行 CLIrunner.invoke() 的情况下将输入传递给 click.confirm
- python - 使用 lxml 在根元素之前/之后添加或添加 PI