I have a question: What´s the better approach to limit the scope in Javascript: Using a namespace like this:
var NAMESPACE = {};
NAMESPACE.foo = function() {
console.log('Hello');
}
NAMESPACE.foo();
or should I use the self-invoking function like this
(function() {
function foo() { console.log('Hello'); }
foo();
})();
Is it always good to have a namespace or can I omit it if I just use one big self-invoking function where I put all my stuff?
A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console.
Self-Invoking Functions A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.
Both of your code samples have very different applications.
NAMESPACE.foo = function(){}
and (function(){})()
are both function expressions and (just as function declarations) delimit the inner scope and have access to vars/functions in their outer scopes.
The main difference is, with the namespace you can call the function anywhere that is in the same scope as the namespace, while the IIFE will only be executed when encountered.
There is no "best practice" without context, so I'll give some examples:
for
loop), an IIFE will cause a performance loss (and is not recommended by JSLint, or anyone in fact). It's better to have a defined function object which you call multiple times than creating a new function object for each iteration.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