0
下面的代碼是javascript obeserver模式,但是當它執行「subject.subscribeObserver(observer1);」時,出現「無法讀取未定義的屬性推送」的錯誤,似乎是我無法訪問subject.observers。爲什麼會發生?在subscribeObserver函數中,我保留this.observers引用,但主題實例仍然無法訪問它。當我使用原型模式但不返回對象模式時,它真的讓我困惑。Javascript觀察者模式不能訪問私有屬性
var Subject = function() {
this.observers = [];
return {
subscribeObserver: function(observer) {
console.log(this);
this.observers.push(observer);
},
unsubscribeObserver: function(observer) {
var index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
},
notifyObserver: function(observer) {
var index = this.observers.indexOf(observer);
if (index > -1) {
this.observers[index].notify(index);
}
},
notifyAllObservers: function() {
for (var i = 0; i < this.observers.length; i++) {
this.observers[i].notify(i);
};
}
};
};
var Observer = function() {
return {
notify: function(index) {
console.log("Observer " + index + " is notified!");
}
}
}
var subject = new Subject();
var observer1 = new Observer();
var observer2 = new Observer();
var observer3 = new Observer();
var observer4 = new Observer();
subject.subscribeObserver(observer1);