首页 > 解决方案 > 箭头运算符 VS 在函数中传递参数:有什么区别?

问题描述

//component.ts放入箭头操作符和放入函数有
什么区别。ii

this.service.getuser().subscribe(i => {
    this.myuserList = i;
});

// 如下图,下面的代码数据数据没有绘制在html页面中

this.service.getUserList().subscribe(function(i : any){
    this.myuserList = i;
});

// 也放上html代码供参考

//component.html 
<tr *ngFor = 'let p of myuserList'>
<td>{{p.username}}</td>
<td>{{p.address.suite}}</td>
</tr>

标签: angulartypescript

解决方案


在使用function(ES5 语法)时,this 关键字将引用函数定义。在使用胖箭头=>(ES6 语法)时,this 关键字指的是外部函数。

function fun1() {

   let someVar = 1; 

   someFunctionWithCallback(function() {
      // this keyword referes to function passed to callback
      // cannot access outside variables here
      console.log(someVar) // undefined
   });

   someFunctionWithCallback(() => {
      // this keyword referes to outside function
      console.log(someVar) // will be accessible e.g. 1
   });
}

推荐阅读