首页 > 解决方案 > 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 上下文,甚至是可能的。

提前致谢。

标签: javascriptbind

解决方案


推荐阅读