can someone please explain to me the following JavaScript design pattern example and what it’s trying to accomplish?
var Knockback = { };
Knockback.Observables = (function () {
function Observables(model, mappings_info, view_model) {
this.model = model;
this.mappings_info = mappings_info;
this.view_model = view_model;
//logic in here
}
Observables.prototype.destroy = function () {
//logic in here
this.view_model = null;
this.mappings_info = null;
return this.model = null;
};
return Observables;
})();
Knockback.observables = function(model, mappings_info, view_model, options) {
return new Knockback.Observables(model, mappings_info, view_model, options);
};
Knockbackis a namespace. Values are stored insideKnockbackso they do not clash with any global variables.Observablesis a constructor sitting insideKnockback. All of the logic is inside a closure ((function () {})()) for modularityobservalesis used as a method of returning an instance ofObservables, This is a way that people can use whats known as “scope safe constructors”. In javascript if you call a constructor without new, then the this object defaults to thewindow, polluting your global namespace again.I’m not sure how much you know about javascript, but I hope this helps.
——————————– updated ————–
1) The closure functions the same as without a closure, that is correct (At the time of my answer i didnt know that there were no “private” variables). But this pattern also allows you to place this constructor wherever you please. Imagine if the namespace (Knockback) name changed to KB. You could place the constructor there without even needed to change a line of code inside the closure.
2) The Knockback.observer function may be a bloat (which i personally dont think it is) but the “scope safe” factor is considered a best practise. consider:
Id like to point out that the boys as ES5 camp fixed this problem, but strict mode is not implemented in all browsers yet (IE.. ahem ahem)