Javascript支持此上下文绑定

Javascript支持此上下文绑定,javascript,bind,Javascript,Bind,我试图理解bind方法,并编写了以下代码: // //窗口上下文 函数Hello(d){ //这总是引用调用上下文 控制台日志(d); } 你好(“ABC”); 函数学生(sname){ this.name\u n=sname; this.hello=你好; this.printAfter2Seconds=printAfter2Seconds.bind(this); this.print=函数(){ log(`Student Name:${this.Name\u n}`); } } print

我试图理解bind方法,并编写了以下代码:

//
//窗口上下文
函数Hello(d){
//这总是引用调用上下文
控制台日志(d);
}
你好(“ABC”);
函数学生(sname){
this.name\u n=sname;
this.hello=你好;
this.printAfter2Seconds=printAfter2Seconds.bind(this);
this.print=函数(){
log(`Student Name:${this.Name\u n}`);
}
}
printAfter2Seconds=函数(){
log(`Before Set TimeOut-${this.name\u n}`);
//让那=这;
setTimeout(函数(){
//console.log(this);
log(`After Set TimeOut-${this.name\u n}`);
},2000);
}
职能部门(dname){
this.name\u n=dname;
this.hello=你好;
this.printAfter2Seconds=printAfter2Seconds.bind(this);
}
让s=新生(“ABC”);
s、 你好(s.name_n);
s、 printAfter2Seconds();
设d=新部门(“IT”);
d、 你好(d.name);
d、 printAfter2Seconds();

//
如果沿着
.bind
路线,您需要
.bind
传递到
setTimeout
的函数(或链接问题的答案所示的其他解决方案之一),因为这是
更改的第二次机会。但在现代JavaScript中,您应该使用。您可以将它附加到setTimeout的右括号中,如:}.bind(this),但如前面提到的@T.J.Crowder,箭头函数会更好。@Durga let that=this没有问题;但是我假设bind解决了,让它=这个;陈述对吗?@T.J.Crowder谢谢。是的,我知道箭头的功能。但我试图理解箭头函数解决的问题。所以我试图理解bind。@T.J.Crowder非常感谢您提到这些差异:)