从这里:https://angular.io/tutorial/toh-pt4 - hero.component.ts
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
我明白这个 heroes => this.heroes = Heroes
翻译如下:
f( heroes )
{
return this.heroes = heroes;
}
这里是否隐含了return
?
我想了解这个内部函数是从哪里调用的。谁在叫它?
最佳答案
在您提供的示例代码中,要返回英雄列表,我们必须这样写
getHeroes(): Hero[] {
this.heroService.getHeroes()
.subscribe(heroes => ({heroes : heroes}));
}
上面的箭头功能将转换为
f( heroes )
{
return this.heroes = heroes;
}
否则,您提供的代码只是对 this.heros 变量进行赋值,因此 return 语句不适用,并且箭头函数将转换为
f( heroes )
{
this.heroes = heroes;
}
箭头函数的进一步解释
箭头函数与函数表达式一样,可用于返回对象字面量表达式。唯一需要注意的是,主体需要用括号括起来,以便区分块和对象(两者都使用大括号)。
示例
//ES5
var setNameIdsEs5 = function setNameIds(id, name) {
return {
id: id,
name: name
};
};
// ES6
var setNameIdsEs6 = (id, name) => ({ id: id, name: name });
console.log(setNameIdsEs6 (4, "Kyle")); // Object {id: 4, name: "Kyle"}
对于常规函数,如果“this”关键字位于对象的方法(属于对象的函数)内,它将引用该对象。在箭头函数中,“this”始终引用其所在函数的所有者。在箭头函数的 return 之前添加 console.log(this) 将返回一个 Window 对象。
示例
// ES5
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: function() {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the Dim sum with Jasmine tea please."
// ES6
const brunch = {
food: 'Dim sum',
beverage: 'Jasmine tea',
order: () => {
return `I'll have the ${this.food} with ${this.beverage} please.`
}
}
brunch.order(); //"I'll have the undefined with undefined please."
关于javascript - 如何在 Angular 中调用用 => 定义的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61811090/