I see a lot of code here, here:
var module = (function (module) {
module.prototype.something_else = function () {
};
return module;
})(module);
Why var module = part present at all? And why return module; if previous part is not needed?
I see usage of:
var module = (function(module) {...})(module || {});
for cases when module wasn't already defined sometimes... Is that above case?
This block of code is only used if module is already defined and you want to extend it (e.g., add a new method):
var module = (function (module) {
module.prototype.something_else = function () {
};
return module;
})(module);
It accepts module as an input parameter and returns the extended module. The assignment of var module = then replaces the original module.
Answering your questions one by one:
Why var module = part present at all?
In the example above (taken from your first URL), var module = is not necessary. The simple example they provide is silly. You could accomplish the exact same thing with this:
module.prototype.something_else = function () {};
Using the above pattern to extend a class makes more sense with the examples provided in your second URL ( http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html ):
var MODULE = (function (my) {
var old_moduleMethod = my.moduleMethod;
my.moduleMethod = function () {
// method override, has access to old through old_moduleMethod...
};
return my;
}(MODULE));
Immediate executing function creates a new scope where we can preserve the old method var old_moduleMethod = my.moduleMethod;
Next question:
And why return module; if previous part is not needed?
You need return module because otherwise the function wouldn't return anything and the var module = assignment would be set to an undefined value.
Next question:
for cases when module wasn't already defined sometimes... Is that above case?
Yes, that is the case. If module isn't defined then you would need to pass in an empty object. However, you typically would use a pattern to extend an object if it isn't defined in the first place. That would make no sense and would just complicate your code.
To understand, it helps to rename identifiers to get the equivalent
var module = (function (module_impl) {
module_impl.prototype.something_else = function () {
};
return module_impl;
})(module || {});
module_impl is the object that is to hold the module's public API. So after populating it, the anonymous function returns it to the caller, which assigns it to the global module. This way the API is now available using module while any implementation details are hidden in the closure created by the anonymous function.
module || {} now is to allow augmentation: the first time it gets called, module is still undefined since the assignment to the return value of the anonymous function has not happened yet. Thus `module || {} evaluates to the second operand.
To further illustrate why the assignment is needed. The first time, the stub gets called, it is effectively the same as
var module = (function () {
var module_impl = {};
// ...
return module_impl;
})());
Related
I have JavaScript Closure methods I need to convert in to TypeScript. I am not able to do that. Please help me. How to write a function inside
a function in TypeScript?
var postPonedMethod1 = function() {
var postPonedMethod2 = function() {
this.getClaimNotices();
this.gridServices.get();
//$scope.gridServicesReciepts.get();
$scope.setDataLoading(false);
};
postPonedMethod2();
}
Your problem is the use of this: postPonedMethod2 refers to this, but it isn't a function defined on a class or object. If you're using popular TypeScript options --noImplicitThis or --strict, TypeScript will complain, because it is possible that you will eventually call postPonedMethod2 in a way that does not provide the expected this instance. In fact, in JavaScript's "strict mode" ("use strict";) you might find that this is undefined where it wasn't before.
In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example:
function f2() {
'use strict'; // see strict mode
return this;
}
f2() === undefined; // true
If possible, I'd switch to defining your AngularJS component as a class, calling this.postPonedMethod1() and this.postPonedMethod2() for clarity.
In general in TypeScript, the solution is to type the "this" outside a class is to define an argument called this as your function's first parameter, which tells TypeScript what type to expect. To temporarily get through the problem, though, you can explicitly set this: any. This defeats the purpose of TypeScript here, because any provides no type checking at all, but it would allow you to solve the problem later in a different commit.
That fixes the typing, but you'll still need to ensure that the value of this is set correctly where you call postPonedMethod2. This would mean one of:
Using an arrow function () => { instead of function () { for postPonedMethod2. An arrow function explicitly does not redefine this.
Calling bind(this) where postPonedMethod2 is defined, or using call as in postPonedMethod2.call(this) where you call it.
Avoiding "use strict" with --noImplicitUseStrict, if you're otherwise trying to emit a module.
Saving the outer value of this to a place where it won't be redefined, as I show below.
var postPonedMethod1 = function() {
var postPonedMethod2 = function() {
this.getClaimNotices(); // error: 'this' implicitly has type 'any' because it does not have a type annotation.
this.gridServices.get(); // error: 'this' implicitly has type 'any' because it does not have a type annotation.
//$scope.gridServicesReciepts.get();
$scope.setDataLoading(false);
};
postPonedMethod2();
}
var fixedPostPonedMethod1 = function(this: any) { // Do better than "any" if you can.
var component = this; // Store the enclosing "this".
var postPonedMethod2 = function() {
component.getClaimNotices();
component.gridServices.get();
//$scope.gridServicesReciepts.get();
$scope.setDataLoading(false);
};
postPonedMethod2(); // You could also call "bind".
}
It works for me like below
var postPonedMethod1 = () => {
var postPonedMethod2 = () => {
this.getClaimNotices();
this.gridServices.get();
//$scope.gridServicesReciepts.get();
$scope.setDataLoading(false);
};
postPonedMethod2();
}
Are there any (non-trivial/ugly hack) ways to call a 'private' method from outside a class/module itself?
Please don't ask why I need this.
Just my personal curiosity and trust in power of doing anything in JS :)
function Module () {
var privateMethod = function () {
alert('1');
};
var publicMethod = function () {
privateMethod();
alert(2);
};
return {
pm: publicMethod
};
}
var m = new Module();
m.pm(); // can i call m.privateMethod() here somehow?
DON'T TRY THIS AT HOME
So you've been warned, now look at this (fiddle; I've replaced all the alerts with console.log() for the greater good):
var methodName = 'privateMethod';
var mSource = Module.toString();
var methodPattern = new RegExp(methodName + '\\s*=\\s*function[^]*?\\{([^]+?)\\};');
var privateMethodSource = mSource.match(methodPattern);
var privateMethodRebuilt = new Function([], privateMethodSource[1]);
privateMethodRebuilt();
It's one possible way to do this with HUGE number of restrictions. First, this particular snippet doesn't even try to parse the arguments, assuming that the method in question doesn't need any. Second, you won't be able to access the other private variables defined within the Module (as the code rebuilds only the particular function, not the environment).
Surely, you can take it further - and rebuild the Module itself, making the target method public (for example, by adding the private function into the exposed methods' list). The question is, WHY on Earth do you even think about needing such thing as using the private method outside the module?
I am trying to wrap my head around different Module pattern declinations. I see different ways of writing these modules and exposing their data.
I'm expecting information on advantages/disadvantages, better patterns not described here, use cases for each of them.
A) Object literal wrapped in a self invoking function, firing off with an init method: (source)
(function() {
var MyModule = {
settings: {
someProperty: 'value';
}
init: function() {
someMethod();
}
someMethod: function() {
// ...
}
};
MyModule.init();
})();
This is an example of a simple "Tweet This" utility I built. Am I using this pattern correctly? So far it's the only one that I have actual experience in writing.
B) Module as a namespaced self-invoking anonymous function: (source)
var MyModule = (function () {
var MyObj = {}
function privateMethod() {
// ...
}
MyObj.someProperty = 1;
MyObj.moduleMethod = function () {
// ...
};
return MyObj;
}());
Are there any advantages/disadvantages over the previous style? Also, what would be the implications of using object literal notation here instead of the dot syntax in the example? Object literal seems cleaner and easier, but I'm not really aware of the proper use cases for each?
C) Module as a namespaced self-invoking anonymous function, but only exposing desired results through a return block: (source)
var MyModule = (function() {
var myPrivateVar, myPrivateMethod;
myPrivateVar = 0;
myPrivateMethod = function(foo) {
console.log(foo);
};
return {
myPublicVar: "foo",
myPublicFunction: function(bar) {
myPrivateVar++;
myPrivateMethod(bar);
}
};
})();
Similar to the previous style, but instead of exposing an entire object with all of it's properties/methods, we're just exposing specific bits of data through a return statement.
D) Module as a function wrapped in a self-invoking anonymous function, with nested functions acting as methods. The module is exposed through the window object, then constructed via the new keyword: (source)
(function(window, undefined) {
function MyModule() {
this.myMethod = function myMethod() {
// ...
};
this.myOtherMethod = function myOtherMethod() {
// ...
};
}
window.MyModule = MyModule;
})(window);
var myModule = new MyModule();
myModule.myMethod();
myModule.myOtherMethod();
I'm assuming the strength of this pattern is if the module is a 'template' of sorts where multiple entities may need to exist within an application. Any specific examples of a good use case for this?
All of these are using the same pattern just in slightly different ways.
A) Object literal wrapped in a self invoking function, firing off with an init method:
This is fine if you don't intend to allow anyone else to access a chunk of code. You don't even have to have an init function. Wrapping your code in an IIFE (immediately invoked function expression) prevents global namespace pollution and allows the use of "private" variables. In my opinion, this is just good practice, not a module.
B) Module as a namespaced self-invoking anonymous function:
This is what people mean when they're talking about the module pattern. It gives you private variables and functions then exposes those through a public interface. That interface just so happens to be called MyObj in your example.
C) Module as a namespaced self-invoking anonymous function, but only exposing desired results through a return block:
This is actually exactly the same thing a B. The only difference is that methods on the interface can't directly reference the interface itself like you can in B. Example:
MyObj.methodA = function() {
return MyObj.methodB();
};
That will work with the previous example because you have a name to reference it but is only useful when you expect public methods to be called using anything other than the returned object as the execution context. i.e, setTimeout(MyModule.methodA) (that will be called with the global context so this.methodB() would not work as intended.
D) Module as a function wrapped in a self-invoking anonymous function, with nested functions acting as methods. The module is exposed through the window object, then constructed via the new keyword:
Same thing as the previous 2 except for 2 minor differences. window is passed as an argument because it has historically been true that it's faster to access a local variable than a global variable because the engine doesn't have to climb up the scope chain. However, most JS engines these days optimize accessing window since it's common and a known object. Likewise, undefined is given as a parameter with nothing passed as an argument. This ensures you have a correct undefined value. The reasoning behind this is that technically, you can assign any value to undefined in non-strict mode. Meaning some 3rd party could write undefined = true; and suddenly all of your undefined checks are failing.
The other difference is that you're returning a function instead of an object. The bonus behind this is that you can have private variables which are shared in each instance of an object, as well as private variables per instance. Example:
var count = 0;
function MyObject(id) {
var myID = id;
count++;
// Private ID
this.getID = function() {
return myID;
};
// Number of instances that have been created
this.getCount = function() {
return count;
};
}
The downside to this is that you aren't attaching methods to the prototype. This means that the JS engine has to create a brand new function for every single instance of the object. If it was on the prototype, all instances would share the same functions but could not have individual private variables.
Is it possible to override the global require function, affecting it at process level?
From what I know, the require function is provided as argument in the function that wraps the NodeJS scripts:
(function (..., require, __dirname) { // something like this
// The wrapped code
})(...);
Is there any way to modify the require function?
(function () {
var _require = require;
require = function () {
console.log("...");
_require.apply(this, arguments);
};
})();
This will probably affect only the script where it's located.
How can we modify it at the process level?
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function(){
//do your thing here
return originalRequire.apply(this, arguments);
};
mock-require does this by overriding Module._load (which is what the real require actually calls).
Here is a much safer native ES6 answer based on #orourkedd which acts like an event listener on all require calls, It might look like its replacing require but if you look closer its actually saying: require = require and trap calls to it but return original behaviour. This is just one of the millions of uses of Proxy() which has been really handy for me, for example in Typescript for mapping tsconfig "paths" with the real module node will resolve.
I would go as far as to say that this is not "Monkey patching" as its on a lower level of the language.
var Module = require('module');
Module.prototype.require = new Proxy(Module.prototype.require,{
apply(target, thisArg, argumentsList){
let name = argumentsList[0];
/*do stuff to ANY module here*/
if(/MyModule/g.test(name)){
/*do stuff to MY module*/
name = "resolveAnotherName"
}
return Reflect.apply(target, thisArg, argumentsList)
}
})
This is the workaround I found. If there is any better solution, I'm open to see it.
I created a script named req-modifier.js:
module.exports = function (_args) {
var _require = _args[1];
function newRequire () {
console.log("Require is called");
return _require.apply(this, arguments);
}
newRequire.__proto__ = _require;
_args[1] = newRequire;
};
Then from the files I want to modify the require function, I do:
require("./req-modifier")(arguments);
var foo = require("./foo");
The limitation is that I have to call every time the req-modifier function.
I'm wondering what's the different between new module and not new module when using RequireJs. What's the different? and which one should I use. For example I have this module
define('somemodule', [], function() {
var module = function() {
var method = function() {
return "something";
}
return {
method : method
};
};
return module;
});
// Use the module (import)
require(['somemodule'], function(somemodule){
console.log(new somemodule().method());
console.log(somemodule().method());
});
http://jsfiddle.net/noppanit/fpT9K/1/
In your example, it does not matter, if you call somemodule with or without new!
Why?
Because your contructor returns a new object and does not make use of this.
But if we translate your example as followed..
var module = function() {
var method = function() {
return "something";
}
this.method = method;
};
.. it works the same. Now if you call module with new, the tiny this refers to a new scope. Because new creates a new scope for your constructor.
Because of that you can use your module like this:
var myInstance = new module();
myInstance.method(); // will output "something"
But now, if you call module without new, the this will refer to the global scope, which is the window object in a browser.
var myInstance = module();
myInstance.method(); // will cause an error
method(); // will output "something" which is not what you wanted.
So?
The new prefix makes sure, your module gets it's own scope. But as I said, your example with module returning an object and not using this, it does'nt matter either you use new or not.
How to prevent functions from being called without new?
Stick to widely used naming conventions: constructors are Capitalized.
And in bigger projects you should test if the constructor function is called with new:
var Module = function() {
// simply check if "this" is an instance of "module"
if (! (this instanceof Module)) {
// and if not, call "module" again, with the "new" prefix
return new Module();
}
var method = function() {
return "something";
}
this.method = method;
};
Just as with any other function, calling via new instantiates a new object for the value of this in the function. When you call it without new, as in the second call, the value of this will be that object returned from the main module function.
As to which you should use, that depends on what "method" expects to be able to do with this. It might not matter at all, or it might matter a lot; it depends on the actual code and the design of your system.