JavaScript Patterns: Build Better Applications with Coding and Design Patterns
All
Stack Overflow 18
This Year
Stack Overflow 1
This Month
Stack Overflow 2
No there's no need since Javascript is a Prototypal based language, meaning that classes are not involved. You are just creating clones of the objects.
http://en.wikipedia.org/wiki/Prototype-based_programming
As far as the concept of type, the type is object.
A good read for more info about this would be Javascript Patterns by Stoyan Stefanov he has several different creational patterns that address your concerns, including examples that implement Design Patterns from the gang of four's design patterns. http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752
Actually the code in your example (the first one) is not the best thing you can do if you're defining all these functions in the global scope (like properties/methods of the global object window). I prefer using module pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript I recommend you to read the whole book in the upper link. Another thing which is extremely useful - Stoyan Stefanov's JS Patterns book http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752.
Another alternative of your example (the second one) is self-executing function:
Self-executing functions are helping you to do some initialization work when loading the page for first time. You can attach events or/and do another stuff which you should do once. It's preventing you from polluting the global scope and doing init multiple times.
There are common JavaScript patterns in this code:
The Namespace Pattern
In a browser, the window object is the global scope object. In this example of code that you shared, the programmer created a immediately-invoked function expression and passes the global object
window
as a parameter, which in the context of the IIFE is bound to the local variableglobal
.The function, as it names suggests, is immediately invoked when this file is parsed by the browser.
From this point on,
global
is just an alias for the global scope objectwindow
, and the programer uses it to define a namespaceapp
in it.The namespace basically avoids cluttering the global scope with the objects you need to define and allows the programmer to be more in control of exactly what is defined within his custom scope.
The idea is that from this point forward, you should define all application globals within this customised scope and not within the window global scope, by this avoiding name collisions with other third-party libraries that you are using. This will be a pseudo-equivalent of packages or namespaces in other languages like Java or C#.
Stoyan Stefanov in his book JavaScript Patterns explains it as follows:
The Immediate Function Pattern
The immediately-invoked function is another common JavaScript pattern. It is simply a function that is executed right after it is defined.
Stefanov describes its importance as follows:
Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the
exports
object.There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class?
As a beginner there are very good books for JavaScript:
They are short and will give you a very good insight of the JavaScript Language.
Not sure if this falls under the category "micro-optimization". I would say no.
But it depends on how often you call
doStuff
. If you call it often, then creating the function over and over again is just unnecessary and will definitely add overhead.If you don't want to have the "helper function" in global scope but avoid recreating it, you can wrap it like so:
As the function which is returned is a closure, it has access to
doMoreStuff
. Note that the outer function is immediately executed ((function(){...}())
).Or you create an object that holds references to the functions:
More information about encapsulation, object creation patterns and other concepts can be found in the book JavaScript Patterns.
Nowadays, answers given here are not entirely complete/correct.
Starting from ES5, the literal syntax behavior is the same as
RegExp()
syntax regarding object creation: both of them creates a new RegExp object every time code path hits an expression in which they are taking part.Therefore, the only difference between them now is how often that regexp is compiled:
RegExp()
syntax - every time new object gets createdSee, for instance, Stoyan Stefanov's JavaScript Patterns book:
If you run this sample in all modern browsers or NodeJS, you get the following instead:
Meaning that every time you're calling the
getRE()
function, a newRegExp
object is created even with literal syntax approach.The above not only explains why you shouldn't use the
RegExp()
for immutable regexps (it's very well known performance issue today), but also explains:The
storedRegExp
is about 5 - 20% percent faster across browsers thaninlineRegExp
because there is no overhead of creating (and garbage collecting) a newRegExp
object every time.Conclusion:
Always create your immutable regexps with literal syntax and cache it if it's to be re-used. In other words, don't rely on that difference in behavior in envs below ES5, and continue caching appropriately in envs above.
Why literal syntax? It has some advantages comparing to constructor syntax:
(Free citation from the same Stoyan Stefanov's JavaScript Patterns book).
Hence, it's always a good idea to stick with the literal syntax, unless your regexp isn't known at the compile time.
A constructor is just a normal function. There is nothing special about it inherently.
All functions have a property called
prototype
.If you write
JavaScript does something special with your function when it executes it.
It sets the value of
this
inside the function body to bemyInstance
. Additionally, it creates a reference toMyFunction.prototype
and stores it as an internal property ofmyInstance
.When your code is executing, the rule that the interpreter follows is such that, if you try to access a property on
myInstance
that it can't find, it will follow that reference to the function'sprototype
and look there. This forms a chain, known as the prototype chain that leads all the way up toObject.prototype
.Here's an example:
The snippet above works, but if you run:
console.log(myDog)
you'll see that it does not have a speak method. the speak method was found in it's prototype.This means that all 'instances' of
Dog
that are created will all share the samespeak
method.So, If I create another dog, it will be able to speak aswell:
It also means that if I change the value of
Dog.prototype.speak
at run time, all instances will be affected.Note: technically, functions do have a
constructor
property but it's not that important and it would just confuse you more if I tried to explain it here.I suggest you read the mozilla docs
Additionally, I suggest you read this book. You'll learn a lot about proper design.
Also note that this is just one way to achieve code re-use. You don't have to go through prototypes at all. In fact JavaScript has methods that let you supply arbitrary values as the value of
this
to functions as an argument.This means that, even though my pet lizard can't normally speak, I can just borrow the method from
Dog.prototype
by utilizing a method likecall()
orapply()
. (All functions have these methods because they 'inherit' them fromFunction.prototype
.)On a related note, there was some interesting discussion right here on HN with regards to Addy Osmani's JS Patterns eBook - http://news.ycombinator.com/item?id=2762888
http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp...
Boom. Get it while it's hot.