Encounter following lines of code, but couldn't understand it.
What is this (/.../)(this); purpose in javascript? Does it have name for this pattern?
Code as below:
//Move.js
(function(exports){
exports.Move = function(){
};
})(this);
They are proven solutions, easily reusable and expressive. They lower the size of your codebase, prevent future refactoring, and make your code easier to understand by other developers.
The book explores the capabilities and pitfalls of object-oriented programming, and describes 23 useful patterns that you can implement to solve common programming problems. These patterns are not algorithms or specific implementations.
Module pattern. 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.
this pattern is an "Immediately Invoked Function Expresssion". in short, it's just a function that is executed immediately. the this
on the end is a parameter to be sent to the inner function that will be accessed as exports
(function(exports){
//that was "this" outside, is now "exports" in here
}(this));
in your example, we can assume that whatever this
was, it's some object that has been added a Move
method to it.
some also call this pattern the "Module Pattern" in a sense that it creates a "contained environment" so that the stuff inside it is not visible to the due to a new function scope. in other words, whatever is inside sees the outside, but the outside can only see what the inside lets it see
That pattern simply makes exports
assigned to this
at the time of execution.
Assuming the global scope and a browser, this
will point to the window
object.
With those assumptions in mind, window.Move
should contain the function assigned inside of that IIFE (Immediately Invoked Function Expression).
If this function were called in a different context where this
is not window
, it will assign that method to whatever this
was in the outer environment.
This pattern is called "Module Pattern". There are various sub patterns and this one used Augmented Module pattern.
First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:
For more read about this Module pattern check out http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
For more reading about general Javascript patterns check out http://addyosmani.com/resources/essentialjsdesignpatterns/book/
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