0

类似于这个问题,但我似乎已经有了选定的答案。我有以下...

import {Component, OnDestroy} from '@angular/core';
import {MdIconRegistry} from "@angular2-material/icon/icon-registry";
import {MD_ICON_DIRECTIVES} from "@angular2-material/icon/icon";
import {ShowcaseCardComponent} from "./showcase-card/showcase-card.component";
import { WheelService } from "../../wheel/wheel.service";
@Component({
    selector: 'jg-showcase',
    template: String(require('./showcase.component.pug')),
    styles: [String(require('./showcase.component.styl'))],
    directives: [MD_ICON_DIRECTIVES, ShowcaseCardComponent],
    viewProviders: [MdIconRegistry]
})
export class ShowcaseComponent implements OnDestroy{
    currentCard: number = 0;
    subscription: any;
    cards = [
        {
            number: 0,
            color: "blue",
            content: "<h1>Card1</h1>"
        },
        {
            number: 1,
            content: "<h1>Card2</h1>"
        }
    ];
    constructor(wheelService: WheelService){
        this.subscription = wheelService.wheelEmitter.subscribe((data: any) => {
           if(data.direction > 0 && this.currentCard !== this.cards.length){
               this.currentCard++;
           }
           else if(this.currentCard){
               this.currentCard--;
           }
           console.log("Current Card "+this.currentCard);
        })
    };
    ngOnDestroy() {
        this.subscription.dispose();
    };
}

问题是this检查器中未定义但我看到了正确的console.log ...

Current Card 1
Current Card 2

为什么控制台说它未定义

this.currentCard
VM10154:1 Uncaught TypeError: Cannot read property 'currentCard' of undefined(…)
4

1 回答 1

1

这与箭头函数在 TS 中的实现方式有关。 thisin 箭头函数是词法推断的,因此它更符合以下代码

function Person() {
  var self = this; // Some choose `that` instead of `self`. 
                   // Choose one and be consistent.
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

所以在箭头函数内部,它实际上并不是this一个更接近的上下文self。这可能不是实际的实现,但更接近于让您了解正在发生的事情。

现在在 Inspector 中,当您键入 this 时,它位于 close/arrow 函数之外,因此无法获得正确的上下文,因此 Inspector 将向您显示undefinedwindow或某些global object

这应该可以解释为什么您的代码可以正常工作,但 Inspector 没有给您预期的价值。

Protip看看你的转译 JS 你的箭头函数是如何转换的。

于 2016-07-03T15:01:40.747 回答