Reputation:
So I am building a little app and my JavaScript code is based off the Module pattern because I think it's a really clean method of coding in JavaScript. However I have seen two examples one which uses the below code and the other does not:
return {
someMethod: someMethod,
otherMethod: otherMethod
}
What is the purpose to the above code and is it needed?
Upvotes: 0
Views: 36
Reputation: 58601
// create an scope by declaring anonymous function and immediately executing it
// the return value will be assigned to myModule...
var myModule = (function(){
// return the parts of the scope to be exposed publicly
return {
someMethod: someMethod,
otherMethod: otherMethod
}
function someMethod(item){ return myPrivateSquareFunction(item) * 2; };
function otherMethod(item){ return item * 5; };
// private function can be called from in the module's scope, but not externally
function myPrivateSquareFunction(item){ return item * item; }
})();
// now, out here you can call `otherMethod`, and `someMethod` (which itself calls `myPrivateSquareFunction`) but you can not call `myPrivateSquareFunction`...
console.log(someMethod(3)); // 18
console.log(otherMethod(3)); // 15
console.log(myPrivateSquareFunction(3)); // ERROR!
By using this pattern, you can choose what implementation details remain private, and what needs to be exposed to the module. This helps you to break up your code into discreet chunks that can be worked on and tested in isolation without the rest of the application complicating it's function. Then, when you have lots of small chunks of code that do their own job correctly, and properly separated, it is an easier task to manage to assemble them into a more complex application.
Upvotes: 0
Reputation: 113994
It's merely returning an object. The code:
return {
someMethod: someMethod,
otherMethod: otherMethod
}
is exactly identical to:
var someObject = {
someMethod: someMethod,
otherMethod: otherMethod
}
return someObject;
Upvotes: 1