Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.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
Javascript 如何将上下文绑定到传递的参数-回调函数?_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 如何将上下文绑定到传递的参数-回调函数?

Javascript 如何将上下文绑定到传递的参数-回调函数?,javascript,angular,typescript,Javascript,Angular,Typescript,传递参数时,上下文将丢失给函数。如何将其绑定到我的typescript文件中 import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class

传递参数时,上下文将丢失给函数。如何将其绑定到我的typescript文件中

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";

  getName(): string {
    return this.name;
  }

  onAction(cb: Function) {
    return cb();
  }
}

<p>
  {{onAction(getName)}}
</p>
从“@angular/core”导入{Component};
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:[“/app.component.css”]
})
导出类AppComponent{
name=“Angular”;
getName():字符串{
返回此.name;
}
onAction(cb:函数){
返回cb();
}
}

{{onAction(getName)}

错误:无法读取未定义的属性“name”

如果在模板中进行绑定,那么这将起作用

<p>
  {{onAction(getName).bind(this)}}
</p>

{{onAction(getName).bind(this)}

但是我想在控制器中创建链接


如果有任何帮助,我将不胜感激

如果我理解正确,您可以在
AppComponent
中的构造函数中进行绑定:

export class AppComponent {
    name = "Angular";

    constructor() {                             // ***
        this.getName = this.getName.bind(this); // ***
    }                                           // ***
  
    getName(): string {
      return this.name;
    }
  
    onAction(cb: Function) {
      return cb();
    }
}

“如果您在模板中进行绑定,那么这将起作用。”我认为不会,它将
.bind(this)
放在了错误的位置。它不应该是
{{onAction(getName.bind(this))}
相关的:这里
onAction
的目的是什么?为什么不直接执行
{{getName()}
呢?请注意,除非使用
OnPush
更改检测策略,否则不要在模板中使用函数。这是一个巨大的性能损失(因为基本上每个可能的更改都会运行更改检测,因为它不知道是否需要重新评估函数),并且,取决于您在内部函数中所做的操作,可能会导致生命周期挂钩中的其他问题。