gpt4 book ai didi

Angular 5 : Service Getter Why Double Arrow if Referenced to Getter instead of Calling Getter Directly

转载 作者:太空狗 更新时间:2023-10-29 18:28:39 25 4
gpt4 key购买 nike

我有一项服务正在加载我想在多个组件之间共享的基本系统信息。

如果我在 getter 中创建一个 getter 方法 this 如果我不在服务中使用双箭头,则 getter 中的 this 成为组件的 this

服务

import { Injectable } from '@angular/core';

@Injectable()
export class WhoAmIService {

constructor() { }
whoAmI = 'I\'m a service'
getterOne(): string {
return this.whoAmI
}
getterTwo = (): string => {
return this.whoAmI
}

}

组件

import { Component } from '@angular/core';
import { WhoAmIService } from './who-am-i.service';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
whoAmI = 'I\'m a component'
getterOne: Function
getterTwo: Function
constructor(
private whoAmIService: WhoAmIService
) {
this.getterOne = whoAmIService.getterOne
this.getterTwo = whoAmIService.getterTwo
console.log('cool', whoAmIService.getterOne())
console.log('cool', whoAmIService.getterTwo())
console.log('why is this different', this.getterOne())
console.log('cool', this.getterTwo())
}
}

https://stackblitz.com/edit/angular-xxsven

问题

如果我将 getter 函数分配给组件,为什么还需要箭头函数?

最佳答案

每当将函数分配给任何其他变量时,实际上复制函数定义并充当具有相同代码的新函数。

你可以认为它是原始函数的克隆。

现在重要的是 context 函数被执行的位置。所以 this 只是 context 它正在执行的位置。

现在让我们回到你的例子

  1. whoAmIService.getterOne() - 在 whoAmIService 内部执行,因此 context (this)指向 whoAmIService
  2. this.getterOne() - 这里 this 将指向 AppComponent 类,因为上下文是 AppComponent

注意:这与 Angular 无关。它的 Javascript 概念。

只需访问此网站了解更多信息 - https://hackernoon.com/execution-context-in-javascript-319dd72e8e2c

关于 Angular 5 : Service Getter Why Double Arrow if Referenced to Getter instead of Calling Getter Directly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com