Secrets of the JavaScript Ninja -- 1

[b]Chapter 3

Scoping and functions[/b]

[u]Scoping rules in Javascript:[/u]

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:


[img]http://dl.iteye.com/upload/attachment/0079/4413/2b3d0529-5ef9-3c41-94a2-f7adf0ccc794.jpg[/img]

[u]Invocations[/u]
There 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.


[b]Summary:[/b]

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值