sách gpt4 ăn đã đi

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

In lại 作者:太空狗 更新时间:2023-10-29 18:28:39 26 4
mua khóa gpt4 giày nike

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

如果我在 getter 中创建一个 getter 方法 cái này 如果我不在服务中使用双箭头,则 getter 中的 cái này 成为组件的 cái này

Phục vụ

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

@Injectable()
export class WhoAmIService {

người xây dựng() { }
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

câu hỏi

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

câu trả lời hay nhất

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

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

现在重要的是 bối cảnh 函数被执行的位置。所以 cái này chỉ một bối cảnh 它正在执行的位置。

现在让我们回到你的例子

  1. whoAmIService.getterOne() - 在 whoAmIService 内部执行,因此 bối cảnh (cái này)指向 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/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress