Secrets of the JavaScript Ninja -- 1
Chapter 3
Scoping and functionsScoping rules in Javascript:1. Variable declarations are in scope from their point of declaration to the end of the function within which they are declared, regardless of block nesting.
Look at this example:
if(window){
var x = 13;
}
alert(x); // 13
2. Named functions are in scope within the entire function within which they are declared, regardless of block nesting.
function outer {
alert(typeof inner === 'function', "inner() in scope before declaration");
function inner() { return "inner";}
alert(typeof inner === 'function', "inner() in scope after declaration");
}
3. For the purposes of declaration scopes, the global context acts like one big function encompassing the code on the page.
And for the code snippet below, what's the scope for each function and variable?
function outer(){
var a = 1;
function inner(){ /* does nothing */ }
var b = 2;
if (a == 1) {
var c = 3;
}
}
outer();
Answer:
InvocationsThere are actually four different ways to invoke a function, each with their own nuances.
They are:
1. As a function, in which the function is invoked in a straightforward manner.
2. As a method, which ties the invocation to an object, enabling object-oriented
programming.
3. As a constructor, in which a new object is brought into being.
4. Via their apply() or call() methods
Difference between 1 & 2:
When using 2, *this* scope is the caller.
How is 3 implemented?
Invoking a function as a constructor is a powerful feature of JavaScript because when a
constructor is invoked, the following special actions take place:
? A new empty object is created.
? This object is passed to the constructor as the this parameter, and thus becomes the
constructor’s function context.
? In the absence of any explicit return value, the new object is returned as the
constructor’s value.
Summary:o When invoked as a simple function, the context is the global object
(window).
o When invoked as a method, the context is the object owning the method.
o When invoked as a constructor, the context is a newly allocated object.
o When invoked via the apply() or call() methods of the function, the
context can be whatever the heck we want.