javascript - 为什么这里需要 'this' 关键字?它指的是什么?

标签 javascript angular object angularjs-scope this

我正在学习 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/

相关文章:

javascript - 更改特定索引处的 React State 数组

javascript - 如何(本地)从 PHP(在 Raspberry Pi 上)调用 JavaScript 函数

javascript - 带有 typescript 的Videojs插件

java - 为什么这个文本面板给我一个内存地址?

javascript - 将键值对转换为所需对象的数组

java - 如何在Jhipster中配置热重载?

JavaScript:DOM 文本节点

javascript - 导航时列表项淡入淡出

javascript - Node Express 未获取 bootstrap.js 文件

Angular 预引导(第一个屏幕)加载器的动画在初始加载期间卡住