Patterns of CommonJS Modules? [duplicate] - javascript

This question already has answers here:
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 5 years ago.
I have been doing some exercises on the interesting "level up your coding" site, Exercism.io and they use the CommonJS style modules for their code samples and testing with Jasmine. I've always thought modules were a hassle I didn't want to deal with, but in these bite size chunks, they look like they could be very useful to begin using in my Single Page Applications. So I've been Googling around and searching Github for some good samples for using CommonJS Modules - and still haven't found one that explains in detail what the main patterns are, and how they differ. For example, one answer I submitted looked like this:
var HelloWorld = function () {};
HelloWorld.prototype.hello = function () {
return 'Hello, World!'
};
module.exports = HelloWorld;
But another one looked like this
var Bob = function () {
this.hey = function (input) {
input = input.split('');
if (input.indexOf('!') >= 0) {return 'Whoa, chill out!'}
if (input.indexOf('?') >= 0) {return 'Sure.'}
return 'Whatever.'
};
}
module.exports = Bob;
Specifically I'm wondering what the difference is between nesting a function inside the parent definition, as done with the Bob hey() function, as opposed to the way the HelloWorld hello() uses the prototype instead.

To start with the two functions you gave as examples are completely different from each other and have different purposes.
Based off of the code you have as an example, the way you are calling them is also incorrect.
For your Bob example, all you are doing is assigning a function to a variable. In order to call it, you simply have to do Bob(). If you do a Bob.hello() you are going to get an error.
The HelloWorld on the other is not just a function, well.. It is, since you declared it as an empty function that is what it will call if you do HelloWorld(). However you defined hello as it's prototype function, for you to invoke that directly you would have to do HelloWorld.prototype.hello(). I reckon that these are used mainly to alter behaviours of existing objects or functions.
You are asking what are the most efficient ways of writing modules, but in reality there is not right answer for that. All a module is is a piece of code that can be exported and reused by other files. They can be functions, objects, simple variables whatever you'd like!
So basically you can do all these:
// moduleThatExportsANumber.js
module.exports = 1
// moduleThatExportsAnObject.js
module.exports = {}
// moduleThatExportsAFunction.js
module.exports = function () { return 'say somethign!'}
// main.js Lets call all the modules!
const number = require('./moduleThatExportsANumber)
const object = require('./moduleThatExportsAnObject)
const function = require('./moduleThatExportsAFunction)
console.log(number) // 1
console.log(object) // {}
console.log(function) // function () { return 'say somethign!'}
console.log(function()) //say somethign!
The whole thing about modules is simply writing stuff in a file, exporting that stuff, which in the case of CommonJS is done through module.exports = [whatever you are exporting], and later importing, which for CommonJS is require('./filename')
Now... Going back to the original thing that was asked, your cheatsheet. I don't know any CommonJS ones unfortunately, however here is a decent blog post about the CommonJS module system and here is a JavaScript one that you may like as well.

Related

Calling a function with a string as the command / dynamic Function Name? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I'm working full-stack on a project, and I've run into a bit of a situation that I think I'll need to resolve fully so I can re-use it in future projects (fairly new to Node, but tons of programming languages and syntax under my belt), so a dirty fix might not be the best (eval()?) I have 3 files, here is an example of the logic:
// main.js
const call = require('./test.js');
config = require('config');
configObj = config.get('Site')
sites = Object.keys(configObj);
siteObj = config.get('Site' + "." + sites[0]); // This only calls Amazon, but in the real project it is a dynamic element
var callCommand = "call." + siteObj.functionCall + "(siteObj)"; // evaluates as call.amazon(siteObj)
setTimeout(() => {callCommand;}, 1500); // This does not work
setTimeout(() => {call.amazon(siteObj);}, 1500); /// This works
// default.json
{
"Site": {
"Amazon": {
"homePage": "https://www.amazon.com/",
"functionCall": "amazon"
}
}
// test.js
function amazon(siteObj) {
// some code
console.log("reached the function");
}
Basically, I'm going to be calling different functions from main.js, targeting the test.js. I need the function call to be dynamic, because it is based on the Site's callFunction key. For instance, once there are 10 sites, maybe it would call "call.xxxxxxx(siteObj)", instead. The string creating the call does not seem to be working, I think because it's a String and the line is looking for a function to execute. I get that, but again, I'm fairly new to Node/JS in general and I'm not exactly sure how to even word the question. I thought simply placing the proper text of the function call as a string would cause JS to execute that text, but I guess not.
Am I missing something simple? I know I will need dynamic function calls in the future of this project, and others, so while I can write logic in test.js or main.js to work around THIS example, writing separate function calls for each Site:
if (sites[0]) {call.amazon(siteObj);
if (sites[1]) {call.ebay(siteObj);
for instance, will get cumbersome, as the Sites list will only grow.
Therefore, we created the callFunction key to try and give each object it's exact call.
I'm not sure if it's parenthesis placement, or the way arrow functions work for the setTimeout, or what it is, but I've tried different instances of:
setTimeout(() => {call.$(siteObj.functionCall)(siteObj);}, 1500); // This does not work
setTimeout(() => {call.$(siteObj.functionCall)(siteObj))); }, 1500) // This does not work
I'm not sure how to use a regular variable, or an object's key properly in this instance to fetch "amazon", especially with the (siteObj) parameter.
and things like that. I am hoping more to be able to one-liner it like that SOMEHOW, but I don't know all of the tricks of this language yet.
I've also tried:
var callCommand = "call." + siteObj.functionCall + "(siteObj)"; // evaluates as call.amazon(siteObj)
var codeToExecute = callCommand;
var tmpFunc = new Function(codeToExecute);
setTimeout(() => {tmpFunc(); }, 1500);
With the above, I get "call" is not defined.
It works with the explicit text in there (call.amazon(siteObj)), but I need that "amazon" to be dynamic, preferably called from it's config key (even if I need to turn that key into a json formatted function).
I know this a huge wall of a read, but it is my first post here. Thanks in advance! Hopefully I formatted and named this post correctly without causing too much of a headache, I apologize if I did.
So, am I missing something simple? I feel like I am, but I'm not new to coding at all, and I am alone on this project (no other developers), and I'm trying to keep it good practice without too many, or any, dirty workarounds. Thank you!
setTimeout(() => {callCommand;}, 1500);
That evaluates the string and does nothing.
You can dynamically call the function from the exported object:
call[siteObj.functionCall](siteObj)
This way you access the object with the functions, that is the module exported, using the property that holds the function, and call it
const call = require('./test.js');
Is giving you something similar to
{
amazon: function() {}
}
Which is just an object
And as you want to dynamically access it, you have to use brackets instead of the dot notation, which allows you to access an object using a variable

"JavaScript: The Good Parts"-way to implement prototype methods?

Having read this article https://www.toptal.com/javascript/es6-class-chaos-keeps-js-developer-up and subsequently "JavaScript: The Good Parts", I shall henceforth commit to becoming a better JavaScript developer. However, one question remained for me. I usually implemented methods like this:
function MyClass(){
this.myData = 43;
this.getDataFromObject = function(){
return this.myData;
}
}
MyClass.prototype.getDataFromPrototype = function(){
return this.myData;
}
var myObject = new MyClass();
console.log(myObject.getDataFromObject());
console.log(myObject.getDataFromPrototype());
My assumption that underlies this whole post is that getDataFromObject is faster (during call, not during object creation) because it saves an indirection to the prototype but it is also less memory-efficient because every object gets an own instance of the function object. If that is already wrong, please correct me and you can probably stop reading here.
Else: Both article and book recommend a style like this:
function secretFactory() {
const secret = "Favor composition over inheritance [...]!"
const spillTheBeans = () => console.log(secret)
return {
spillTheBeans
}
}
const leaker = secretFactory()
leaker.spillTheBeans()
(quote from the article, the book didn't have ES6 yet but the ideas are similar)
My issue is this:
const leaker1 = secretFactory()
const leaker2 = secretFactory()
console.log(leaker1.spillTheBeans === leaker2.spillTheBeans) // false
Do I not mostly want to avoid that every object gets an own instance of every method? It might be insignificant here but if spillTheBeans is more complicated and I create a bazillion objects, each with twelvetythousand other methods?
If so, what is the "goot parts"-solution? My assumption would be:
const spillStaticBeans = () => console.log("Tabs rule!")
const spillInstanceBeans = (beans) => console.log(beans)
function secretFactory() {
const secret = "Favor composition over inheritance [...]!"
return{
spillStaticBeans,
spillInstanceBeans: () => spillInstanceBeans(secret)
}
}
const leaker1 = secretFactory()
const leaker2 = secretFactory()
leaker1.spillStaticBeans()
leaker2.spillInstanceBeans()
console.log(leaker1.spillStaticBeans === leaker2.spillStaticBeans) // true
console.log(leaker1.spillInstanceBeans === leaker2.spillInstanceBeans) // false
The spillInstanceBeans method is still different because each instance needs its own closure but at least they just wrap a reference to the same function object which contains all the expensiveness.
But now I have to write every method name two to three times. Worse, I clutter the namespace with public spillStaticBeans and spillInstanceBeans functions. In order to mitigate the latter, I could write a meta factory module:
const secretFactory = (function(){
const spillStaticBeans = () => console.log("Tabs rule!")
const spillInstanceBeans = (beans) => console.log(beans)
return function() {
const secret = "Favor composition over inheritance [...]!"
return{
spillStaticBeans,
spillInstanceBeans: () => spillInstanceBeans(secret)
}
}
}())
This can be used the same way as before but now the methods are hidden in a closure. However, it gets a bit confusing. Using ES6 modules, I could also leave them in module scope and just not export them. But is this the way to go?
Or am I mistaken in general and JavaScript's internal function representation takes care of all this and there is not actually a problem?
My assumption that underlies this whole post is that getDataFromObject is faster to call than getDataFromPrototype because it saves an indirection to the prototype
No. Engines are very good at optimising the prototype indirection. The instance.getDataFromPrototype always resolves to the same method for instances of the same class, and engines can take advantage of that. See this article for details.
Do I not mostly want to avoid that every object gets an own instance of every method? It might be insignificant here
Yes. In most of the cases, it actually is insignificant. So write your objects with methods using whatever style you prefer. Only if you actually measure a performance bottleneck, reconsider the cases where you are creating many instances.
Using ES6 modules, I could also leave them in module scope and just not export them. But is this the way to go?
Yes, that's a sensible solution. However, there's no good reason to extract spillInstanceBeans to the static scope, just leave it where it was - you have to create a closure over the secret anyway.
The spillInstanceBeans method is still different because each instance needs its own closure but at least they just wrap a reference to the same function object which contains all the expensiveness.
It should be noted that you're just replicating the way the JavaScript VM works internally: a function like spillTheBeans is compiled only once where it occurs in the source code even if it has free variables like secret. In SpiderMonkey for example, the result is called a »proto-function« (not to be confused with prototype). These are internal to the VM and cannot be accessed from JavaScript.
At runtime, function objects are created by binding the free variables of proto-functions to (a part of) the current scope, pretty much like your spillInstanceBeans example.
Saying that, it's true that using closures instead of prototype methods and this creates more function objects overall – the robustness gained from true privacy and read-only properties might make it worthwhile. The proposed style focuses more on objects rather than classes, so a different design could emerge that cannot be compared directly to a class-based design.
As Bergi says, measure and reconsider if performance is more important in (some part of) your code.

How to "take variables out of an object" in javascript

I'm looking for something that will import the contents of an object to the global scope:
var y = {}
y.x = 5
//do some magic here
console.log(x); //5
I want to do this is so I can make an easy to use module with memorable function names without having to worry about things accidentally getting overridden by other modules.
Consider this example:
funModule = {};
funModule.washClothes = function(clothes){...}
funModule.walkDog = function(dogName){...}
//etc
funModule.UNITED_STATES_DEFICIT = ...;
Here I've created a module that has some useful functions and constants (implementations and values were replaced with "...").
I don't want my users to have to type out the module name every time they call function or use a constant. That would result with really messy code:
funModule.walkDog(funModule.UNITED_STATES_DEFICIT);
I could try it again by defining everything globally:
washClothes = function(clothes){...}
walkDog = function(dogName){...}
//etc
UNITED_STATES_DEFICIT = ...;
but if a different module has also defined the commonly named function washClothes we've got trouble. (in my actual case the commonly named function is run)
Removed from technical context, here is the problem I'm faced with:
Firstly I want to use simple and memorable names to make the module easy to learn and fun to use.
Secondly I don't want the easy names to make the module impossible to use with others. Especially as it grows, a lot of common names will be used. It would be great if the users could decide whether or not import the names directly.
Thirdly I realized as I'm typing this that what I'm describing is something that definitely already exists, in python. See http://effbot.org/zone/import-confusion.htm for more detail.
tl;dr How can python-like imports be done with javascript?
EDIT:
It seems there is not a universal way to do this.
Using Window won't work in all environments (but will work in any common browser).
Apparently ES6 Modules are not available to web browsers directly.
This question is different from this one because its not about Node.js. I was looking for a universal way to do it, but that doesn't seem possible, so I'll limit it to web browsers, (namely chrome, firefox, safari, opera, and maybe ie)
EDIT:
This general article about Scope could be useful for anyone with a similar question as mine: https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/
Object.prototype.makeglobal=function(){
for(key in this){
if(window[key]){//replace window if youre not in a browser
//already exist, error handling
console.error(key+' already exist in window');
}else{
window[key]=this[key];
}}};
Use like this:
funModule.makeglobal();
//now you can
washClothes();
But this is bad as it pollutes the global object.
2.Your user should create his own namespace:
function(){
this.washClothes();
//more of his content
}.call(funModule);
3.You could also add a loader:
funModule.load=function(func){
console.log(func);
console.log(this);
func.call(this,this);
};
Now you can do:
funModule.load(function(fun){
this.washClothes();
fun.washClothes();
});
4.If youre concerned about readability you may use function chaining (?):
funModule.washClothes=function(){
//your code
return this;
}
now you can do:
funModule.washClothes("tshirts").washClothes("trousers").washClothes();
ES6 Modules are what you want.
If you will define your object as es6 module you could do this (using the names in your example):
import { washClothes } from "fun-module";
and then washClothes will be globally available on the file that imported it, just like you want.
Read about it here.
If you really want a magic solution like in the comment in your post and don't want to use ES6 and you run in the browser you can put it on the window object:
window.x = 5
In JavaScript, at least in a browser, global variables are properties of the window object: that is, window.x and x (where x is global) reference the same value. So, in theory, you could use Object.assign() to copy your object's properties to the window object making them global variables. This is roughly equivalent to globals().update(myobj.__dict__) in Python.
But just as import * is usually a bad idea in Python, so too this sounds like a bad idea, except even worse because window has a lot of other properties that you probably don't want to clobber.
After some additional research I found a way, without polluting the global namespace, to allow users to directly access module contents.
This solution allows the user to:
Write code that directly references the module's functions/properties
Define precedence if there are multiple modules written in this same style
Still access the module's functions/properties by module name*
*This feature comes with a catch
Here's the code
Module
funModule = {};
//This stuff is the arbitrary contents of the module:
funModule.washClothes = function(clothes){...}
funModule.walkDog = function(dogName){...}
//etc
funModule.UNITED_STATES_DEFICIT = ...;
//etc
//This part is necessary:
funModule.run(userApp)
{
for(key in this){
eval(key + " = " + this[key] + ";");
}
userApp();
}
The only way (that I could find) to dynamically define functions both in funModule.run's scope and in funModule is to use Eval. Using call, apply, or bind to manipulate scope would still require use of the this keyword and the whole point of this unusual style is to make client code as simple and non-repetitive as possible.
Client Code 1
function myApp()
{
washClothes(UNITED_STATES_DEFICIT);
}
funModule.run(myApp);
Here in the client code it is possible to directly access everything except for funModule.run. So the global namespace is kept clean but the user's code does not need unnecessary repetition.
Client Code 2
function myApp()
{
washClothes(UNITED_STATES_DEFICIT);
}
funModule.run( otherModule.run.bind({},myApp) ); //otherModule has precedence here
Assume otherModule is a different module that features the same run function. funModule will load its contents then call its first argument. The first argument will load otherModule's contents, overriding anything from funModule with the same name.
Client Code 3
function myApp()
{
//directly access stuff from funModule
walkDog()
var big = UNITED_STATES_DEFICIT * 3.14;
//explicitly access stuff from specific modules
clothes = new otherModule.Clothes();
funModule.washClothes(otherModule.washClothes(clothes));
}
funModule.run(myApp)
This is the feature that makes use of eval necessary. The user can opt out of ambiguity of direct access. They can still access properties/methods by naming the module they come from.
But Why?
Some StackOverflow users were understandably concerned about the unusual set of constraints in the question, so I figured I would answer the following question:
Why don't you use a short alias for your module.
I tried to answer that question in this article, which pulls from this question and answer.

JavaScript module pattern with example [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I can't find any accessible examples showing how two (or more) different modules are connected to work together.
So, I'd like to ask whether anyone has time to write an example explaining how modules work together.
In order to approach to Modular design pattern, you need to understand these concept first:
Immediately-Invoked Function Expression (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
Here are using function expression.
What is namespace?
Now if we add the namespace to the above piece of code then
var anoyn = (function() {
}());
What is closure in JS?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
jsfiddle for the code above.
The objective is to hide the variable accessibility from the outside world.
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.
I come from a c# background so have added some terminology I find useful from there.
Html
You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).
You need add files to the project with script tags like this:
<script type="text/javascript" src="app/native/MasterFile.js" /></script>
<script type="text/javascript" src="app/native/SomeComponent.js" /></script>
It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!
Namespace file
MasterFile.js
myAppNamespace = {};
that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).
Module(s)
SomeComponent.js
myAppNamespace.messageCounter= (function(){
var privateState = 0;
var incrementCount = function () {
privateState += 1;
};
return function (message) {
incrementCount();
//TODO something with the message!
}
})();
What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.
Concepts
I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.
I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.
You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.
Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/

Examples of practical javascript object oriented design patterns

What object oriented design patterns do you use in your application's javascript, and why?
Feel free to post code, even if there is no formal design pattern attached to it.
I have written plenty of javascript, but I have not applied much object orientated patterns to what I am doing, and I am sure i am missing a lot.
The following are three popular JavaScript patterns. These happen to be easily implementable because of closures:
The Module Pattern - Example (and made popular) by Eric Miraglia
Memoization - Example by Oliver Steele
Currying - Example by Dustin Diaz
You may also want to check out:
Pro JavaScript Design Patterns by Ross Harmes and Dustin Diaz
The following is a Google I/O talk from 2008 presented by Diaz, where he discusses some topics from his book:
Google I/O 2008 - Design Patterns in an Expressive Language
Inheritance
I use a notation for inheritance that is based on ExtJS 3, which I find works pretty close to emulating classical inheritance in Java. It basically runs as follows:
// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
move : function() {alert('moving...');}
});
// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
bark : function() {alert('woof');}
});
// Instantiate Lassie
var lassie = new Dog();
// She can move and bark!
lassie.move();
lassie.bark();
Namespaces
I also agree with Eric Miraglia on sticking to namespaces so the code above should be run within its own context outside the window object, this is critical if you intend your code to run as one of many concurrent frameworks / libraries executing in the browser window.
This means that the only way to the window object is via your own namespace / module object:
// Create a namespace / module for your project
window.MyModule = {};
// Commence scope to prevent littering
// the window object with unwanted variables
(function() {
var Animal = window.MyModule.Animal = Object.extend(Object, {
move: function() {alert('moving...');}
});
// .. more code
})();
Interfaces
You can also make use of more advances OOP constructs such as interfaces to enhance your application design. My approach to these is to enhance the Function.prototype in order to get a notation along these lines:
var Dog = Object.extend(Animal, {
bark: function() {
alert('woof');
}
// more methods ..
}).implement(Mammal, Carnivore);
OO Patterns
As for 'Patterns' in the Java sense, I've only found use for the Singleton pattern (great for caching) and the Observer pattern for event-driven functionality such as assigning some actions when a user clicks on a button.
An example of utilising the Observer Pattern would be:
// Instantiate object
var lassie = new Animal('Lassie');
// Register listener
lassie.on('eat', function(food) {
this.food += food;
});
// Feed lassie by triggering listener
$('#feeding-button').click(function() {
var food = prompt('How many food units should we give lassie?');
lassie.trigger('eat', [food]);
alert('Lassie has already eaten ' + lassie.food + ' units');
});
And thats just a couple of tricks in my bag of OO JS, hope they are useful to you.
I recommend if you intend to go down this road that you read Douglas Crockfords Javascript: the Good Parts. Its a brilliant book for this stuff.
I am a fan of the Module Pattern. It's a way of implementing extensible, non-dependent (most of the time) frameworks.
Example:
The framework, Q, is defined like this:
var Q = {};
To add a function:
Q.test = function(){};
These two lines of code are used together to form modules. The idea behind modules is that they all extend some base framework, in this case Q, but are not reliant on each other (if designed correctly) and can be included in any order.
In a module, you first create the framework object if it does not exist (which is an example of the Singleton pattern):
if (!Q)
var Q = {};
Q.myFunction = function(){};
That way, you can have multiple modules (like the one above) in separate files, and include them in any order. Any one of them will create the framework object, and then extend it. No manual need to check if the framework exists. Then, to check if a module/function exists in custom code:
if (Q.myFunction)
Q.myFunction();
else
// Use a different approach/method
The singleton pattern is often very helpful for 'encapsulation' and organization stuff. You can even change accesibility.
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
cleanest way to implement a singleton in javascript
I really like jquery's method chaining pattern, allowing you to call several methods on one object. It makes it really easy to perform several operations in a single line of code.
Example:
$('#nav').click(function() {
$(this).css('color','#f00').fadeOut();
});
I really like the Decorator pattern with jQuery plugins. Rather than modifying plugins to meet your needs, write a custom plugin that just forwards requests and adds additional parameters and functionality.
For example, if you need to pass a set of default arguments around all the time, and you need slightly-different behavior that ties into business logic, write a plugin that does whatever pre and post work is necessary to suit your needs and passes your default arguments if those particular arguments aren't specified.
The main benefit of this is that you can update your libraries and not worry about porting library changes. Your code might break, but there's at least the chance that it won't.
One of useful patterns in javascript world is chaining pattern which is made popular by LINQ at first place, and also is used in jQuery.
this pattern enables us to call different methods of a class in chaining manner.
the main structure of this pattern would be as
var Calaculator = function (init) {
var result = 0;
this.add = function (x) { result += (init + x); return this; };
this.sub = function (x) { result += (init - x); return this; };
this.mul = function (x) { result += (init * x); return this; };
this.div = function (x) { result += (init / x); return this; };
this.equals = function (callback) {
callback(result);
}
return this;
};
new Calaculator(0)
.add(10)
.mul(2)
.sub(5)
.div(3)
.equals(function (result) {
console.log(result);
});
the key idea of this pattern is this key word, which makes possible accessing to other public member of Calculator fucntion.

Categories