I've just started developing in Javascript, and have been reading up on scope and execution context. I was wondering if there's a difference between this:
function fun1 () {
var x = 1;
function fun2 () {
x = x*2;
alert(x);
}
}
and:
function fun1 () {
var x = 1;
fun2(x);
}
function fun2 (x) {
x = x*2;
alert(x);
}
Would there be reasons to use one over the other? Do they have any performance/security implications (or other unexpected implications for beginner JS developers)?
3 Answers 3
The main difference is that at the first case fun2 will be available only in the fun1 scope. At the second case both functions will be available at scope, where their definition is
Comments
If we talk about your first approach, it is not possible to call fun2 because you have enclosed it within fun1 and its scope is local. However you can ammend your fun1 to call fun2 as follows:
var fun1 = (function(){
var x = 1;
var fun2 = function(){
x = x*2;
alert(x);
};
return {
fun2: fun2
}
})();
The above return statement will make your fun2 as public scope that you can call it with the fun1 object as follows:
fun1.fun2();
Please note that the
xvariable is private and only accessible withinfun1function. If you need to access it usingfun1.x, you will have to return it in yourfun1as I've returnedfun2.
This is called modular or enclosed pattern. By this we can achieve encapsulation.
IF we talk about your second approach i.e pretty simple, your fun1 will call fun2 . I hope, it clears the concept.
Comments
In Javascript scope is defined by the enclosing function. That is, code defined within a function is not visible outside the function.
So, in your 1st example, func2 in defined inside func1, and thus is visible only inside func1.
In your 2nd example, it is defined in the global scope (the window object, when running in a browser), and as such is callable from anywhere, just like func1.
fun2in the first example.fun1, inside it's not.fun1