我正在学习 Angular 2,我对“this”关键字感到困惑。考虑下面的代码:
import { Component, OnInit } from '@angular/core';
import { Hero } from '../heroes';
import { HEROES } from '../mock-heroes';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
selectedHero : Hero;
onSelect(hero : Hero) : void{
this.selectedHero = hero;
}
heroes = HEROES;
constructor() { }
ngOnInit() {
}
}
在'onSelect'方法中,为什么我们需要使用'this'关键字来引用'selectedHero'属性?为什么我们不能只使用“selectedHero”而不使用这个关键字?这里的“这个”意味着什么?
最佳答案
您使用“this”来绝对确定它是您引用的正确值。
考虑这样的事情(伪代码):
var hello = 0;
function main () {
var hello = 1;
var self = this;
alert(hello)
if(1 < 2) {
var hello = 2;
alert(hello)
alert(self.hello)
}
}
在这里,我们将首先提醒 1,然后提醒 2,然后提醒 1。我们可以使用“this”来表示,例如保存对其他范围的引用,或者如果您的命名约定在整个代码中非常相似,您可以使用“this”来使代码更清晰。
在你的具体示例中,我 99% 确信使用“this”并不重要,但在某些情况下这是一件非常有用的事情。它似乎只是引用类,因此如果您想从类内部访问您的类,您可以使用“this”作为引用它的快速而简单的方法。这是一个自引用变量,如果这对您有意义的话。
关于javascript - 为什么这里需要 'this' 关键字?它指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48047428/