TypeScript中这两个方法调用的区别是什么?
我第一次写这段代码时,它没有工作,这给了我一个错误:http没有定义TypeScript中这两个方法调用的区别是什么?,typescript,callback,Typescript,Callback,我第一次写这段代码时,它没有工作,这给了我一个错误:http没有定义 importFile(fileId: string, fileName: string): void { this.fileService.importFileById(fileId, fileName, this.refreshFiles); } 第二次我写了这段代码,并做了一些工作,但我不明白有什么区别 importFile(fileId: string, fileName: string): void {
importFile(fileId: string, fileName: string): void {
this.fileService.importFileById(fileId, fileName, this.refreshFiles);
}
第二次我写了这段代码,并做了一些工作,但我不明白有什么区别
importFile(fileId: string, fileName: string): void {
this.fileService.importFileById(fileId, fileName, () => {
this.refreshFiles();
});
}
refreshFiles()中的代码如下所示:
refreshFiles(): void {
this.http.get('api/Files/GetFiles').subscribe(result => {
//etc
}, error => console.error(error));
}
这两段代码之间有什么区别?
为什么第一个代码不起作用而第二个代码起作用?this.refreshFiles和
this.refreshFiles()
之间的区别在于,第一个代码返回对没有上下文的函数的引用(调用此函数时,需要提供this
)而第二个函数则直接调用函数,并隐式地提供这个
您可以做什么:您可以使用this.refreshFiles.bind(this)
显式设置由this.refreshFiles
返回的函数的上下文,并按原样传递它
this.fileService.importFileById(fileId, fileName, this.refreshFiles.bind(this));
您在工作示例中使用的arrow函数非常类似于bind
(事实上,arrow函数是bind
的一种语法糖)
另一个例子:
const test = {
run() {
console.log(typeof this.run)
}
}
console.log(test.run()) // function, because we call it as test.run() and provide test as `this`
let testrun = test.run;
console.log(testrun()) // undefined, because testrun has no `this`
testrun = test.run.bind(test);
console.log(testrun()) // function, because testrun has a bound `this`
知道了!this.refreshFiles-它是指向函数的指针,this.refreshFiles()-它是给定上下文中的函数调用。