Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript中这两个方法调用的区别是什么?_Typescript_Callback - Fatal编程技术网

TypeScript中这两个方法调用的区别是什么?

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 {

我第一次写这段代码时,它没有工作,这给了我一个错误:http没有定义

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()-它是给定上下文中的函数调用。