为什么需要'this'关键字?它指的是什么?

时间:2018-01-01 05:50:19

标签: 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'?这个意味着什么呢?

1 个答案:

答案 0 :(得分:-1)

您使用“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”作为一种快速简便的方法来引用它。这是一个自引用变量,如果这对你有意义的话。

相关问题