此课程将显示此= undefined
。如何传递上下文?
class MeteorAccount implements IService{
constructor() {
Tracker.autorun(function () {
//observe
Meteor.userId());
console.log(this);//undefined
});
}
}
答案 0 :(得分:2)
您有两种选择:
class MeteorAccount implements IService{
constructor() {
Tracker.autorun(function() {
//observe
Meteor.userId());
console.log(this);//undefined
}.bind(this));
}
}
class MeteorAccount implements IService{
constructor() {
Tracker.autorun(() => {
//observe
Meteor.userId());
console.log(this);//undefined
});
}
}
还有另一种选择,我只是不喜欢它,但它是人们在箭头功能之前用来做的事情(不知道为什么不是绑定选项):
class MeteorAccount implements IService{
constructor() {
var self = this;
Tracker.autorun(function() {
//observe
Meteor.userId());
console.log(self);//undefined
});
}
}