typescript单例设计模式:这是未定义的
我在typescript(2.1.6)类中实现了singleton模式,如下所示:typescript单例设计模式:这是未定义的,typescript,design-patterns,singleton,nativescript,Typescript,Design Patterns,Singleton,Nativescript,我在typescript(2.1.6)类中实现了singleton模式,如下所示: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: NotificationsViewModel; private constructor() { this._myS
export class NotificationsViewModel {
private _myService: NotificationService;
private _myArray: [];
private static _instance: NotificationsViewModel;
private constructor() {
this._myService = new NotificationService();
this._myArray = [];
NotificationsViewModel._instance = this;
}
public static getInstance(): NotificationsViewModel {
if (!this._instance) {
this._instance = new NotificationsViewModel();
}
return this._instance;
}
public startListening() {
return this._myService.addUserNotificationChildListener(this.handleNotifications);
}
private handleNotifications(notification: Models.NotificationItem) {
this._myArray.push(notification);// this line breaks
}
}
有趣的是handleNotifications方法失败,出现错误无法读取未定义的属性\u myArray
。基本上是说,这个
——等于实例
——不是实例化的(正确吗?)。
我不明白的是这是怎么可能的,因为这个。_myService
使用起来没有任何问题
我是否以错误的方式实现了该模式?为什么会这样
编辑
以下是调用该类的代码:
notificationsViewModel = NotificationsViewModel.getInstance(mainUser);
notificationsViewModel.initialize().then(() => {
notificationsViewModel.startListening();
}).catch((error) => {
console.dump(error);
});
我没有在上面的代码段中包含
initialize
方法,但它返回了一个承诺。因此这里的问题是经典的“错误的此
上下文”,因为您传递的是对handleNotifications
方法的引用,该方法未绑定到实例
应该是:
public startListening() {
return this._myService.addUserNotificationChildListener(this.handleNotifications.bind(this));
}
或:
此外,无需在构造函数中创建实例:
private constructor() {
this._myService = new NotificationService();
this._myArray = [];
NotificationsViewModel._instance = this; // this is redundant
}
你能添加使用这个类/实例的代码吗?@NitzanTomer当然,马上就来!哦,我明白了!这解决了问题……但有一点我不明白:如果
handleNotifications
方法没有绑定到实例,为什么只有在访问方法内部的数组时才会出错?例如,如果我在handleNotifications`中使用console.log(“foo”),,我不会得到错误。您正在向函数传递一个引用,该引用是有效的引用,因此可以调用它。但是当在函数中使用时,该
将引用与NotificationsViewModel
的实例不同的对象,现在我知道了!!很抱歉打扰您,但我发现这非常有趣,在handleNotifications
方法中,哪个对象是this
绑定到的?那就变了。。如果在浏览器中,可能是窗口
,但很容易找到。只需将console.log(this)
记录下来,看看你得到了什么
private constructor() {
this._myService = new NotificationService();
this._myArray = [];
NotificationsViewModel._instance = this; // this is redundant
}