【问题标题】:using this keyword in angular in nested functions在嵌套函数的角度中使用 this 关键字
【发布时间】:2018-10-22 19:53:18
【问题描述】:

您好,我想知道如何在嵌套函数中使用组件的变量。

这是一个例子:

export class AppComponent implements OnInit {
  name = ['Angular 6','Angular5','Angular4','Angular2'];
  isexist: string[]=[];

ifExist(text){
  var that= this;
  console.log("first ",this);
  var test="test";
  let exist= this.name.map(function (elm){
    if(elm==text) {
      console.log(this);
      this.isexist.push(elm); // works with that.isexist.push(elm); 
      }
      })
}
ngOnInit() {
  this.ifExist('Angular 6');

}

这是我在浏览器开发工具中得到的结果

first  AppComponent {name: Array(4), namev: "helo", isexist: Array(1)};
second undefined

我有一些问题 如何在不使用箭头功能的情况下访问isexist? 为什么第二个this 不包含test 元素?

【问题讨论】:

    标签: javascript typescript ecmascript-6 ecmascript-5


    【解决方案1】:

    在这里尝试 lambda:

    ifExist(text){
      var that= this;
      console.log("first ",this);
      var test="test";
      let exist= this.name.map((elm)=>{
        if(elm==text) {
          console.log(this);
          this.isexist.push(elm); // works with that.isexist.push(elm); 
          }
          })
    }
    

    【讨论】:

    • 是的,箭头功能有效;)但我已经提到过,如何在=> 出现之前获得相同的结果?
    • 这是因为一个叫做闭包的javascript概念。在 javascript 中,每个函数都是一个对象。在 html 5 中的箭头之前,我们必须使用绑定函数。 bind link
    【解决方案2】:

    不使用箭头函数就无法访问ifExists 的原因是箭头函数中的this创建箭头函数的上下文具有相同的值。 p>

    this 但是,在普通匿名函数中,具有 从中调用普通函数的上下文的值(在您的情况下,普通函数的上下文和范围只是内部ifExists 方法。

    【讨论】:

      【解决方案3】:

      根本没有理由循环,因为您只是检查数组是否包含元素。你甚至不会从map() 回来。其他答案已经用this 解释了你的问题,下面是你应该如何重构你的代码(重写为纯 js 以使其在 sn-p 中工作,但你明白了):

      class Foo {
        constructor() {
           this.name = ['Angular 6','Angular5','Angular4','Angular2'];
           this.isexist = [];
        }
        
        ifExist(text) {
          if (this.name.includes(text)) this.isexist.push(text);
        }
        
        runner() {
          this.ifExist('Angular 6');
          console.log(this.isexist);
        }
      }
      
      
      new Foo().runner()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        • 2013-12-01
        • 2018-03-15
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2014-01-10
        相关资源
        最近更新 更多