gpt4 book ai didi

javascript - 这个观察者模式代码有什么问题?

转载 作者:行者123 更新时间:2023-11-30 00:05:27 25 4
gpt4 key购买 nike

我刚刚试用了来自 https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know#observer-design-pattern 的观察者模式代码但它不起作用。它告诉我 this.observers 是未定义的,但我真的不明白为什么?

示例代码如下:

var Subject = function() {
this.observers = [];

return {
subscribeObserver: function(observer) {
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);
subject.subscribeObserver(observer2);
subject.subscribeObserver(observer3);
subject.subscribeObserver(observer4);

subject.notifyObserver(observer2); // Observer 2 is notified!

subject.notifyAllObservers();
// Observer 1 is notified!
// Observer 2 is notified!
// Observer 3 is notified!
// Observer 4 is notified!

最佳答案

请检查这个 fiddle :

var Subject = function() {

this.observers = [];

this.subscribeObserver = function(observer) {

this.observers.push(observer);

},

this.unsubscribeObserver = function(observer) {

var index = this.observers.indexOf(observer);

if(index > -1) {

this.observers.splice(index, 1);

}

},

this.notifyObserver = function(observer) {

var index = this.observers.indexOf(observer);

if(index > -1) {

this.observers[index].notify(index);

}

},

this.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);
subject.subscribeObserver(observer2);
subject.subscribeObserver(observer3);
subject.subscribeObserver(observer4);

subject.notifyObserver(observer2); // Observer 2 is notified!

subject.notifyAllObservers();
// Observer 1 is notified!
// Observer 2 is notified!
// Observer 3 is notified!
// Observer 4 is notified!

在您返回的对象中,观察者未定义,这就是您无法访问 native 方法“push”的原因。

关于javascript - 这个观察者模式代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38709405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com