Why is IIFE required in the following context? - javascript

I am working to emulate the require functionality with a few javascript functions, for example:
// We set up an object that will include all the public modules
// And then a require function which basically just accesses that public module
const modules = {};
function require(moduleName) {
return modules[moduleName];
}
modules['math.js'] = function() {
// hidden implementation details
let incr = x => ++x;
return {
incr,
sum(x,y) { return x+y; }
}
}
Why is it required to do modules['math.js'] = (function() {...})(); and not just a normal non-invoked function call as above?

modules["match.js"] is only a function. You probably want it to be an object:
modules["math.js"] = { ... };
But then you won't have private members or functions you can use! Everything will be public. So to solve this we create a closure:
modules["math.js"] = function () {
let priv = 0;
return { ... };
};
Here's where we are now. To make it a closure AND have modules["math.js"] be a nice object we can use, we immediately call this function:
modules["math.js"] = (function () {
let priv = 0;
return { ... };
})();
Now, modules["math.js"] is an object with members and methods we can use, AND it has a private locally scoped variable named priv that can be used only by the module.
This is similar to ES6 modules where you export a select few values bound to identifiers and everything else in the file is private.

Related

Making JavaScript private methods accessible to its public methods

I understand there are couple of patterns to make JavaScript 'class-like'.
I would like to take the 'extending by prototype' way... simply because it looks more neat. I am not worried about performance much here...
In the below example I have a class (basically function) MetricsChart. I have couple of public methods and one private method (basically a reusable method).
Here from the public method (drawOrAdd) I can't access the private method (_convertArrayToTable), how can I do that?
function MetricsChart(containerId, chartType) {
this._container = document.getElementById(containerId);
this._chartType = chartType;
this._isChartDrawn = false;
this._chartData = null;
var _convertArrayToTable = function (data) {
return google.visualization.arrayToDataTable(data);
}
}
MetricsChart.prototype.drawOrAdd = function(data)
{
if (!this.isChartDrawn()) {
var chart = new google.visualization.LineChart(this._container);
if (chart) {
var table = _convertArrayToTable(data);
console.log(table);
this._isChartDrawn = true;
}
}
}
MetricsChart.prototype.isChartDrawn = function () {
return this._isChartDrawn;
}
MetricsChart.prototype.getChartData = function () {
}
One way I accidentally found was to enclose the public methods inside the MetricsChart class itself...
It works for me :): I can access the public methods outside and the public method can access the private method (serves the purpose).
Below code... Is this right? Am I doing anything wrong?
function MetricsChart(containerId, chartType) {
this._container = document.getElementById(containerId);
this._chartType = chartType;
this._isChartDrawn = false;
this._chartData = null;
var _convertArrayToTable = function (data) {
return google.visualization.arrayToDataTable(data);
}
MetricsChart.prototype.drawOrAdd = function (data) {
if (!this.isChartDrawn()) {
var chart = new google.visualization.LineChart(this._container);
if (chart) {
var table = _convertArrayToTable(data);
console.log(table);
this._isChartDrawn = true;
}
}
}
MetricsChart.prototype.isChartDrawn = function () {
return this._isChartDrawn;
}
MetricsChart.prototype.getChartData = function () {
}
}
So, here a couple of things, in order to understand what you have done precisely.
First of all:
function foo() {
var i = 0;
function bar() {
return true;
}
}
What's happening here: every time the function foo is called, it creates in its scope a new variable i, and a new function bar. The function bar and the variable i are in its scope, it means they're local: there is no way, with this code, to access to either i or bar outside the function foo. Also because, once the function foo is terminated, both i and bar are disposed.
So, this is why you cannot access from your "public" method to the "private" one, and I hope it's more clear now. The only way for a function to access to a function or variable is that there is a reference shared in the same scope. So, this is what you have done in your last example: you define your "public" methods in the same scope where you define your "private" method. In this way they can access each other. However, the way you have done, has a big downside. As I said previously, the function bar is created every time the function foo is called. In a "class" example, it means:
function MyClass() {
function myprivate() {}
MyClass.prototype.mypublic = function () { return myprivate() }
}
It means that every time you're creating an instance of MyClass, you're creating two new functions, and you're rewrite all the time the prototype of your "class". This is far from be a good approach. In fact, if you have something like:
var a = new MyClass();
var _mypublic = a.mypublic;
var b = new MyClass();
console.log(_mypublic === b.mypublic) // false
console.log(_mypublic === a.mypublic) // false too!
So, you guess right but you executed wrong. What you need here is a the "module pattern": nowadays you can use CommonJS module in nodejs or AMD in browser and so on, but the basic idea is defined a "scope" and exports from this scope only what you want. In your case, you could have:
// this is your "module"
;(function(exports) {
// your local (private) function
var _convertArrayToTable = function (data) {
return google.visualization.arrayToDataTable(data);
}
function MetricsChart(containerId, chartType) {
this._container = document.getElementById(containerId);
this._chartType = chartType;
this._isChartDrawn = false;
this._chartData = null;
}
MetricsChart.prototype.drawOrAdd = function(data) {
if (!this.isChartDrawn()) {
var chart = new google.visualization.LineChart(this._container);
if (chart) {
var table = _convertArrayToTable(data);
console.log(table);
this._isChartDrawn = true;
}
}
}
// you decided to exports to the main scope what you want
exports.MetricsChart = MetricsChart;
}(this)); // here `this` is the global object
And that's it. You have created a closure, using the "module pattern", and from the "public" method you can access to the "private" function, because they're defined in the same scope. But because you do not do that in the "class" constructor, you don't redefine them every time you instantiate a new object. Therefore, the previous example written in this way, will give the right result:
var a = new MyClass();
var _mypublic = a.mypublic;
var b = new MyClass();
console.log(_mypublic === b.mypublic) // true
console.log(_mypublic === a.mypublic) // true
What you've done isn't necessarily "wrong"...it just looks weird. Also, you won't be able to access "MetricsChart.prototype.*" until after you've created an instance of "MetricsChart". Depending on how you are using this object, it may not matter.
That being said, another way is to keep your original structure, but move the following outside of the constructor:
var _convertArrayToTable = function (data) {
return google.visualization.arrayToDataTable(data);
}
It would still be private to your module which should be good enough (you are using modules right?).
What you have done works perfectly.
You can't inherit private methods in any OOP language in terms of overriding them or accessing them directly. They are private. So it makes no sense to have them prototyped for inheritance purposes. You have wrapped them in function scope so they are as "private" as they need to be.
To access the private methods use privilege methods. Check this document: http://javascript.crockford.com/private.html.
About your code check this answer:
Setting javascript prototype function within object class declaration
p.s.
function Test()
{
var p = function(pv)
{
//
}
this.e = function (ap) { p(ap) }
}
var n = new Test();
n.e("e"); // It is legal call
n.p(); // will throw
But if you declare a private function in c-tor it will be executed on first creation of object of this type. When declare a methods in prototype this methods are add before any code execution. In general the browser first check the js file to collect all methods for prototype and than execute any code. So when you declare a prototype methods into c-tor this methods will be available only after first creation of the object of those type. ( Sorry for my English ).
Check this situation:
function Test()
{
alert(this.ST_A);//alert undefined
alert(this.ST_B);//alert 2
Test.prototype.ST_A = 1;
alert( this.ST_A)//alert 1
}
Test.prototype.ST_B = 2;
In first pass the browser will populate Test with ST_B and ST_B will be available anywhere any time. After than in second pass the browser will start to execute the code in this time ST_A will not be visible until the browser execute the Test.prototype.ST_A = 1;

Javascript mixins when using the module pattern

I've been using the module pattern for a while, but recently have started wanting to mix in functions and properties into them to increase code re-use. I've read some good resources on the subject, but still am a bit uncertain as to the best approach. Here is a module:
var myModule = function () {
var privateConfigVar = "Private!";
//"constructor"
function module() {}
module.publicMethod = function () {
console.log('public');
}
function privateMethod1() {
console.log('private');
}
return module;
}
And here is a mixin object:
var myMixin = function () {};
Mixin.prototype = {
mixinMethod1: function () {
console.log('mixin private 1');
},
mixinMethod2: function () {
console.log('mixin private 2');
}
};
Ideally, I'd like to mix-in some methods from other objects as private methods and some as public methods, so that I could call some "extend" function, with a param as "private"/"public". So, that
mixin(myModule, myMixin, "private");
makes the myMixin methods available within myModule by just calling mixinMethod1() and have correct scope, and:
mixin(myModule, myMixin, "public");
makes the myMixin methods available within myModule by calling module.mixinMethod1() and have correct scope
I've tried using a method that copies properties from one prototype to another, I've tried the underscore extend method to copy properties of the object from one to to the other, and various things in between. I think I'm a bit turned around regarding scope and prototypes at this point, and would love some direction as to how best to do mixins like this when using the module pattern. Note that it doesn't matter what the object myMixin looks like (whether adding functions to the prototype, or a module itself), I'm just trying to figure out some way to make it work.
Thank!
So that [some code] makes the myMixin methods available within myModule by just calling mixinMethod1() and have correct scope
That's impossible. You cannot modify a scope by calling a function, especially not from outside. See also Is it possible to import variables in JavaScript? for the design reasons of that.
So, what can you do?
From outside the module
Nothing to the private scope(s) of module functions. And you cannot use the private functions of the module, obviously. You can extend its prototype with methods (which is the most common), you can even decorate its constructor function. Within those, you can use your own private functions, either completely static ones or class-specific ones.
var myMixin = (function() {
// everything class-unspecific but mixin-local
var staticMixinVariables, …;
function globalPrivateFunction(){…}
function staticMethod(){…}
return function(mod) {
// everything class-specific
// also using the locals from above
mod.staticHelper = function() { staticMixinVariable … };
mod.prototype.mixinMethod1 = staticMethod;
mod.prototype.mixinMethod2 = function(){…};
…
};
})();
// Example:
myMixin(SomeClass)
From within the module
Using the mixin in the module code itself can allow for much greater flexibility.
var myMixin = (function() {
// everything class-unspecific but mixin-local
…
return {
publicHelper1: function(){…},
publicHelper2: function(){…},
decorateInstance: function(o) {
o.xy = …;
},
extendPrototype: function(proto) {
// everything class-specific
// also using the locals from above
proto.mixinMethod1 = staticMethod;
proto.mixinMethod2 = function(){…};
…
}
};
})();
With such an interface, it becomes easy to construct a class that is using this as a mixin (not inheriting from it):
var myClass = (function() {
function Constructor() {
myMixin.decorateInstance(this);
…
}
Constructor.prototype.method1 = function() { myMixin.publicHelper1() … };
Constructor.prototype.method2 = function() { … };
myMixin.extendPrototype(Constructor.prototype);
Constructor.myHelper = myMixin.publicHelper2; // re-export explicitly
return Constructor;
})();
However, the mixin will never have access to the private class variables, nor can it present a private, class-specific API. Still, we can use dependency injection to provide that access explicitly (and having a mixin factory in effect):
var myClass = (function() {
var … // private class functions and variables
var mixer = myMixin(privateClassHelper,
privateClassVariable,
function setPrivateVar(x) {…},
… );
var myHelper = mixer.customHelper, … // local "aliases"
function Constructor(localX) {
mixer.decorateInstance(this, localX);
…
}
… // further using the class-specific private mixer
return Constructor;
})();
Not all techniques shown above need to be used in every mixin, just choose the ones you need. Not all possible techniques are shown in the above examples, also :-) The mixin pattern can be applied onto a plain module or inside its declaration as well, the above examples have only shown classes with prototypes.
For a few good examples, and a theoretical distinction between (stateless) Traits, (stateful) Mixins and their "privileged" counterparts, have a look at this presentation.
The with keyword can be very usefull to define a scope, but it has also some drawbacks (it is by the way forbidden in strict mode).
Using the with keyword, you can define a private variable privateScope within the body of your module, that would contain all your provate methods :
var myModule = function () {
var privateConfigVar = "Private!";
var privateScope = {};
//"constructor"
function module() {}
var proto = module.prototype;//avoids multiple attribute lookup
//Let's re-define you example' private method, but with a new strategy
privateScope['privateMethod1'] = function() {
console.log('private');
}
proto.publicMethod = function () {
with(privateScope){
//this call should work
privateMethod1();
}
console.log('public');
}
proto.publicMethod2=function(name,fn){
with(privateScope){
//this will be defined later by a Mixin
otherPrivateMethod();
}
console.log('public2');
}
proto.definePrivateFunction=function(name,fn){
privateScope[name] = fn;
}
return module;
}
Your mixin will use the definePrivateFunction we just defined to add private methods to the private scope :
//An example mixin implementation
function Mixin(source,target,flag){
if(flag==="private"){
for(var currentMethodName in source){
target.definePrivateFunction(currentMethodName,source[currentMethod])
}
}else{
for(var currentMethodName in source){
target[currentMethodName]=source[currentMethod];
}
}
}
The following code should work fine:
var test = myModule();
var testInstance = new test();
testInstance.publicMethod();// will call the private method defined internally
Mixin({
otherPrivateMethod:function(){
console.log("other Prvate Method called")
}
},test.prototype,"private");
testInstance.publicMethod2();// will call the private method defined by the mixin
Ideally, I'd like to mix-in some methods from other objects as private methods and some as public methods, so that I could call some "extend" function, with a param as "private"/"public". ...
As it already has been mentioned, there is no way of achieving exactly this goal.
So, that ... makes the myMixin methods available within myModule by just calling mixinMethod1() and have correct scope, and: ... makes the myMixin methods available within myModule by calling module.mixinMethod1() and have correct scope.
And referring to scope ... this is a closed address space created by functions.
Except for closures, scope only is available during a function's runtime
within this function's body. It never ever can be manipulated/spoofed.
The term one is looking for is context. JavaScript, being in many ways highly
dynamic, is build upon late binding (the object/target/context a method is called
on gets evaluated/looked up at runtime) and two kinds of delegation.
Context gets delegated either automatically by "walking the prototype chain"
or explicitly by one of both call methods which every function object does provide
- either call or apply.
Thus JavaScript already at language core level does offer a function based
Mixin pattern that is mightier than any of the available extend(s) or mixin
implementations for it provides delegation for free and is able of passing
around state which almost every of the blamed helpers does lack unless there
was effort of implementing this feature again in a rather roundabout fashion
(or ass-backwards to put it bluntly).
Bergi for his explanation already earned the bounties.
Within his answer's last paragraph there is a link to resources of mine that
already got outdated 3 month after giving the referred talk. Due of not having
enough reputation points, I'm not able to comment his answer directly. For this
I'll take the chance pointing now to the latest state of my personal research and
understanding of »The many talents of JavaScript for generalizing Role Oriented Programming approaches like Traits and Mixins«
Back again answering the OP's question.
I'm going to change the two first given code examples from the assumed module pattern
and the rather exemplarily provided mixin code base towards a plain constructor function
and what I'm meanwhile tempted to call a "proxified" and/or "bicontextual" mixin in order
to boil down the mechanics of delegating two different target/context objects at once.
Thus demonstrating a pure function based mixin pattern that might come closest to what
the OP tries to achieve.
var MyBicontextualMixin = function (localProxy) {
localProxy.proxifiedAccessible = function () {
console.log("proxified accessible.");
};
this.publiclyAccessible = function () {
console.log("publicly accessible.");
};
};
var MyConstructor = function () {
var localProxy = {};
MyBicontextualMixin.call(this, localProxy);
var locallyAccessible = localProxy.proxifiedAccessible;
// call 'em
locallyAccessible(); // "proxified accessible."
this.publiclyAccessible(); // "publicly accessible."
};
(new MyConstructor);
// will log:
//
// proxified accessible.
// publicly accessible.
This special pattern also is the underlying base for composing pure
function based Traits that rely on conflict resolution functionality
provided by "proxified" Mixins that won't expose this functionality
into public.
And for not ending up that theoretical there will be a "real world example",
composing a Queue module out of various reusable mixins that entirely
worship the approach of DRY. It also should answer the OP's question about
how to achieve encapsulation and exposition build only upon the module
pattern and function based mixin composition.
var Enumerable_first_last_item = (function (global) {
var
parseFloat = global.parseFloat,
math_floor = global.Math.floor,
// shared code.
first = function () {
return this[0];
},
last = function () {
return this[this.length - 1];
},
item = function (idx) {
return this[math_floor(parseFloat(idx, 10))];
}
;
return function () { // [Enumerable_first_last_item] Mixin.
var enumerable = this;
enumerable.first = first;
enumerable.last = last;
enumerable.item = item;
};
}(window || this));
var Enumerable_first_last_item_proxified = function (list) {
Enumerable_first_last_item.call(list);
// implementing the proxified / bicontextual [Enumerable_first_last_item] Mixin.
var enumerable = this;
enumerable.first = function () {
return list.first();
};
enumerable.last = function () {
return list.last();
};
enumerable.item = function (idx) {
return list.item(idx);
};
};
var Allocable = (function (Array) {
var
array_from = ((typeof Array.from == "function") && Array.from) || (function (array_prototype_slice) {
return function (listType) {
return array_prototype_slice.call(listType);
};
}(Array.prototype.slice))
;
return function (list) { // proxified / bicontextual [Allocable] Mixin.
var
allocable = this
;
allocable.valueOf = allocable.toArray = function () {
return array_from(list);
};
allocable.toString = function () {
return ("" + list);
};
allocable.size = function () {
return list.length;
};
Enumerable_first_last_item_proxified.call(allocable, list);
};
}(Array));
var Queue = (function () { // [Queue] Module.
var
onEnqueue = function (queue, type) {
//queue.dispatchEvent({type: "enqueue", item: type});
},
onDequeue = function (queue, type) {
//queue.dispatchEvent({type: "dequeue", item: type});
}/*,
onEmpty = function (queue) {
//queue.dispatchEvent({type: "empty"});
}*/,
onEmpty = function (queue) {
//queue.dispatchEvent("empty");
},
Queue = function () { // [Queue] Constructor.
var
queue = this,
list = []
;
queue.enqueue = function (type) {
list.push(type);
onEnqueue(queue, type);
return type;
};
queue.dequeue = function () {
var type = list.shift();
onDequeue(queue, type);
(list.length || onEmpty(queue));
return type;
};
//Observable.call(queue); // applying the [Observable] Mixin.
Allocable.call(queue, list); // applying the bicontextual [Allocable] Mixin.
},
isQueue = function (type) {
return !!(type && (type instanceof Queue));
},
createQueue = function () { // [Queue] Factory.
return (new Queue);
}
;
return { // [Queue] Module.
isQueue : isQueue,
create : createQueue
};
}());
var q = Queue.create();
//q.addEventListener("enqueue", function (evt) {/* ... */});
//q.addEventListener("dequeue", function (evt) {/* ... */});
//q.addEventListener("empty", function (evt) {/* ... */});
console.log("q : ", q); // { .., .., .., }
console.log("q.size() : ", q.size()); // 0
console.log("q.valueOf() : ", q.valueOf()); // []
"the quick brown fox jumped over the lazy dog".split(/\s+/).forEach(function (elm/*, idx, arr*/) {
console.log("q.enqueue(\"" + elm + "\")", q.enqueue(elm));
});
console.log("q.size() : ", q.size()); // 9
console.log("q.toArray() : ", q.toArray()); // [ .., .., .., ]
console.log("q.first() : ", q.first()); // "the"
console.log("q.last() : ", q.last()); // "dog"
console.log("q.item(2) : ", q.item(2)); // "brown"
console.log("q.item(5) : ", q.item(5)); // "over"
console.log("q.dequeue()", q.dequeue()); // "the"
console.log("q.dequeue()", q.dequeue()); // "quick"
console.log("q.dequeue()", q.dequeue()); // "brown"
console.log("q.dequeue()", q.dequeue()); // "fox"
console.log("q.dequeue()", q.dequeue()); // "jumped"
console.log("q.size() : ", q.size()); // 4
console.log("q.toArray() : ", q.toArray()); // [ .., .., .., ]
console.log("q.first() : ", q.first()); // "over"
console.log("q.last() : ", q.last()); // "dog"
console.log("q.item(2) : ", q.item(2)); // "lazy"
console.log("q.item(5) : ", q.item(5)); // undefined
.as-console-wrapper { max-height: 100%!important; top: 0; }

Why can't I declare local variables and functions within a TypeScript class?

In TypeScript, I can't seem to declare a function in a class without the compiler adding it to the prototype. For example:
class MyTypeScriptClass {
// method, is added to prototype
foo1(): void {
alert('invoked foo1');
}
// private method also added to prototype
private foo2(): void {
alert('invoked foo2');
}
//// can I have a local function, without making it a private method?
//function foo3() {
// alert('invoked foo3');
//}
}
The above compiles to this:
var MyTypeScriptClass = (function () {
function MyTypeScriptClass() { }
MyTypeScriptClass.prototype.foo1 = function () {
alert('invoked foo1');
};
MyTypeScriptClass.prototype.foo2 = function () {
alert('invoked foo2');
};
return MyTypeScriptClass;
})();
What I am looking for is typescript that can compile to the following JavaScript:
var fvm = new FlasherViewModel2();
var MyTypeScriptClass = (function () {
function MyTypeScriptClass() { }
MyTypeScriptClass.prototype.foo1 = function () {
alert('invoked foo1');
};
MyTypeScriptClass.prototype.foo2 = function () {
alert('invoked foo2');
};
function foo3() {
alert('invoked foo3');
}
return MyTypeScriptClass;
})();
Can it be done?
(As a side note, I know that foo3 would not be callable from external code. I would actually invoke foo3 from another method within the class, for example, to pass a function to a jQuery fadeOut.)
As apsillers mentions, private static is probably what you want. While it's not supported in current builds, you will be able to have a private static member in TypeScript at some point in the future (the design team changed its mind on this one based on feedback similar to this).
I just discovered another way to have private methods in a typescript class, though the pattern may smell a little funny. As far as I can tell, you can only do this when you wrap the class in a module. For example:
module MyApp {
// not accessible externally, `this` must be passed in if needed
function foo3(that: MyTypeScriptClass): void {
that.foo1();
alert('invoked foo3');
}
// not accessible externally
function foo4(): void {
alert('invoked foo4');
}
export class MyTypeScriptClass {
// normal method, is added to prototype
foo1(): void {
alert('invoked foo1');
}
// private method also added to prototype, is accessible externally
private foo2(): void {
alert('invoked foo2');
foo3(this);
foo4();
}
}
}
The above compiles into:
var MyApp;
(function (MyApp) {
function foo3(that) {
that.foo1();
alert('invoked foo3');
}
function foo4() {
alert('invoked foo4');
}
var MyTypeScriptClass = (function () {
function MyTypeScriptClass() { }
MyTypeScriptClass.prototype.foo1 = function () {
alert('invoked foo1');
};
MyTypeScriptClass.prototype.foo2 = function () {
alert('invoked foo2');
foo3(this);
foo4();
};
return MyTypeScriptClass;
})();
MyApp.MyTypeScriptClass = MyTypeScriptClass;
})(MyApp || (MyApp = {}));
With the above, external javascript could invoke foo2() on an instance of MyTypeScriptClass, but neither foo3() nor foo4() is accessible externally at runtime. The biggest caveat is that if your private method needs access to members of the instance, you have to pass this in as a function parameter. Essentially, these are private static methods.
var instance = new MyApp.MyTypeScriptClass();
// public, accessible externally
instance.foo1();
// will not compile in a .ts file, but works at runtime from manual js file
instance.foo2();
// runtime exception, foo3 is not defined
foo3(instance);
MyApp.foo3(instance);
// runtime exception, foo4 is not defined
foo4();
MyApp.foo4();
This approach also sort of works with scalar variables, but the variables are also essentially static -- you can't have different values for different class instances. To do that, as far as I can tell, you still need to declare them within the class. Marking them private will keep the typescript compiler from allowing external calls to them, but other javascript code can still access them externally.

Unit test private classes

Let's say I made use of the following module-kind pattern in JavaScript:
var myModule = (function () {
var Foo = function () { /* ... */ };
var Bar = function () {
this.foo = new Foo();
};
Bar.prototype.someMethod = function () {
this.foo.someMethod();
};
return {
'Bar': Bar
};
})();
Is it advisable and if yes - how can I expose Foo for unit testing? Is there some common technique or pattern for doing this?
I don't think you should really need to unit test the private members. As long as you have comprehensive tests on the public members, any errors within the private members will manifest themselves as errors on the public members. You can then use good ol' debugging to find out what the exact problem was.
Alternatively, if you have your tests run on a separate build to production, you could expose the enclosing object, and test against that. You'd need to remember to remove the reference to the enclosing object before deployment - or you could automate it somehow. Honestly though, I generally wouldn't bother removing it, unless you're packaging a library for public consumption.
var myModule = (function () {
var _this = this;
var Foo = function () { /* ... */ };
var Bar = function () {
this.foo = new Foo();
};
Bar.prototype.someMethod = function () {
this.foo.someMethod();
};
return {
'Bar': Bar,
'__private__': _this
};
})();
function test_foo(obj) {
var foo = obj.__private__.Foo;
assert(foo.prop, 10)
}
For an inhouse system, being able to access the private data/functions is usually a non-issue, if it is clearly understood that accessing private members should not be done. This is highlighted by providing a reference to the enclosing object with a name like __private__. (Can you tell I'm kinda into Python? ;) )

JavaScript Module Pattern - What about using "return this"?

After doing some reading about the Module Pattern, I've seen a few ways of returning the properties which you want to be public.
One of the most common ways is to declare your public properties and methods right inside of the "return" statement, apart from your private properties and methods. A similar way (the "Revealing" pattern) is to provide simply references to the properties and methods which you want to be public. Lastly, a third technique I saw was to create a new object inside your module function, to which you assign your new properties before returning said object. This was an interesting idea, but requires the creation of a new object.
So I was thinking, why not just use this.propertyName to assign your public properties and methods, and finally use return this at the end? This way seems much simpler to me, as you can create private properties and methods with the usual var or function syntax, or use the this.propertyName syntax to declare your public methods.
Here's the method I'm suggesting:
(function() {
var privateMethod = function () {
alert('This is a private method.');
}
this.publicMethod = function () {
alert('This is a public method.');
}
return this;
})();
Are there any pros/cons to using the method above? What about the others?
Your function has no object context, so this references to the global window object in this case. Every property you assign to this automatically pollutes the global namespace.
(function() {
console.log(this == window); // true
this.publicMethod = function () {
alert('This is a public method.');
}
})();
console.log(publicMethod); // function()
You can explicitly pass it an object to tell which context to use.
var MYAPP = {};
(function() {
// 'this' will now refer to 'MYAPP'
this.publicMethod = function () {
alert('This is a public method.');
}
}).call(MYAPP);
console.log(publicMethod); // undefined
console.log(MYAPP.publichMethod); // function()
Which you can write in somewhat other style:
var MYAPP = (function(my) {
var my;
⋮
return my;
})(MYAPP);
And we arrived to an already discussed pattern. For further details, see Dustin's article on Scoping anonymous functions.
I would recommend the style where you add your public properties and methods to an anonymous object that you then return:
var myModule = (function() {
function privateMethod() { ... }
function publicMethod() { ... }
return { publicMethod: publicMethod };
})();
if you want to publish methods, then do something like:
var export = (function() {
var privateMethod = function () {
alert('This is a private method.');
}
var export = {};
export.publicMethod = function () {
alert('This is a public method.');
}
return export;
})();
Another option is to avoid the this reference altogether. Define a function that creates and returns an anonymous object instead.
function makeThing(someAttribute) {
var privateVariable = 42;
function someMethod() {
return privateVariable;
}
return {
"publicMethodName": someMethod,
"getAttribute": function() {
return someAttribute;
}
};
}
var thing = makeThing(99);
thing.publicMethodName();
thing.getAttribute();
Revealing Module patterns:
var m1 = (function(){ return {method: mthod} })();
var m2 = new function Singleton(){ return {method: mthod} };
var m3 = ({}).prototype = {method: method};
var m4 = ({}).prototype = (function(){ ... })();
var m5 = (function(){}).prototype = {} || (function(){ ... })();
var m6 = (function(extendee){
return extendee.prototype = {attr3: 'attr3'};
})({currentAttr1: 1, currentAttr2: 2});
Also, if you need method-chaining:
var m = (function(){}).prototype = (function(){
var thus = m; // this
console.log('m this-------', thus);
function fn(){
console.log('fn', thus);
return thus;
}
function f(){
console.log('f', thus);
return 'poop';
}
return {f: f, fn: fn};
})();
console.log('M:', m, 'm.fn', m.fn(), 'm.fn.f', m.fn().f());
There's also plenty more ways, and you can protagonize your modules as well.

Categories

Resources