I'm having a bit of trouble figuring out the best way to implement this.
I want a module that has a constructor that takes in an argument that stores it for later use within the module.
var ModuleB = function(moduleA) {
this.moduleA = moduleA;
}
ModuleB.prototype = function() {
//private stuff/functions
function someMethod() {
moduleA.doSomething();
}
//public api
return {
someMethod : someMethod
};
}();
In some other file
//ModuleA defined elsewhere
var moduleA = new ModuleA();
//...
var module = new ModuleB(moduleA);
module.someMethod();
Now above in someMethod
, moduleA is undefined, and this
, is the global window object. Can someone explain how I would get access to moduleA? I don't understand what happens to this.moduleA = moduleA;
after the constructor. I'm not really a javascript developer so if I'm using the wrong pattern here or something, feel free to chime in.
The Revealing Module pattern is a design pattern for Javascript applications that elegantly solves this problem. The central principle of the Revealing Module pattern is that all functionality and variables should be hidden unless deliberately exposed.
In classical object-oriented programming languages, a constructor is a special method used to initialize a newly created object once memory has been allocated for it. In JavaScript, as almost everything is an object, we're most often interested in object constructors.
In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.
The Module pattern is used to mimic the concept of classes (since JavaScript doesn't natively support classes) so that we can store both public and private methods and variables inside a single object — similar to how classes are used in other programming languages like Java or Python.
You are very close, but you're missing something important in your definition of someMethod
.
EDIT: is is easier to tell what works and what doesn't if you change the name of the module property in ModuleB:
var ModuleA = function() {}
ModuleA.prototype = (function () {
return {
someMethod: function () {
return 'foo';
}
};
}());
var ModuleB = function(moduleA) {
this.innerModule = moduleA;
}
ModuleB.prototype = (function () {
return {
doStuff: function () {
return this.innerModule.someMethod();
}
};
}());
var moduleA = new ModuleA();
var moduleB = new ModuleB(moduleA);
console.log(moduleB.doStuff()); // prints "foo"
http://jsfiddle.net/mN8ae/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With