与this question类似,但我似乎已经选择了答案。我有以下......
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(…)
答案 0 :(得分:1)
这与在TS中实现arrow function的方式有关。
箭头函数中的MATCH (user:USER) WHERE user.username IN ['Sara', 'John']
WITH COLLECT(id(user)) AS user_ids
MATCH (user:USER)-[:LIKES]->(car:CAR)
WHERE id(user) IN user_ids
WITH car, user_ids, COLLECT(id(user)) as ids_of_users_that_like_car
WHERE ALL(user_id IN user_ids WHERE user_id IN ids_of_users_that_like_car)
RETURN car
是词汇推断的,所以它更符合下面的代码
this
因此,在箭头函数中,它实际上不是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
的上下文。这可能不是实际的实施,但更接近于让您了解正在发生的事情。
现在在Inspector中,当你输入它时,它在close / arrow函数之外,因此无法获得正确的上下文,因此Inspector会显示self
或undefined
或某些{{1} }
这可以解释为什么你的代码有效,但Inspector没有给你预期的价值。
Protip 查看您已编译的JS箭头函数如何转换。