I haven't used the observer pattern but here are my thoughts:
Calling apply on new just make sense. In JS, the
new
operator effectively creates a blank object and assigns it tothis
. I'm would say that its equivalent toctor.apply({})
except that it won't return the newly constructed object (you'd have to save the object before hand)you could define the ctor before hand and just instantiate helpers:
function App() { function helpers() { var self = this; this.prisoners = function ObserverList() { this.observerList = []; ObserverList.prototype.Add = function (obj) { return this.observerList.push(obj); }; //more stuff }; this.prison = function Subject() { this.observers = new self.prisoners(); Subject.prototype.AddObserver = function (observer) { this.observers.Add(observer); }; //more stuff }; }; this.helpers = new helpers(); this.alcatraz = new this.helpers.prison(); }
But personally if you just want to create types, I'd just declare them as functions in the appropriate scope. Something like:
function App() {
function prisoners() {
this.observerList = [];
ObserverList.prototype.Add = function (obj) {
return this.observerList.push(obj);
};
//more stuff
};
function prison() {
this.observers = new prisoners();
Subject.prototype.AddObserver = function (observer) {
this.observers.Add(observer);
};
//more stuff
};
this.alcatraz = new this.prison();
}