scope, call object

<noscript type="text/javascript" event="FSCommand(info,args)" for="sIFR_callback_2">sIFR_callback_2_DoFSCommand(info, args);</noscript>Scope, the scope chain and closures

But before we get into closures, something about scope. Every JavaScript expression is surrounded in a scope. The scope contains what is available to the expression. When you define a new function, the body of this function exists in a new scope. For example:

function foo(){
    var msg = "hello world";
    alert(msg);
};

foo();

Here alert(msg); works, because msg is defined in the same scope as in which alert is called.

Deep down in the JavaScript interpreter the scope is represented as a call object. This object contains all the variables which have been defined in the scope that the call object represents. When a new scope is created, it's call object is linked to the call object of the scope it was created in. This creates a scope chain.

//我的理解:scope = call object    

This phenomenon is best explained through an example. In JavaScript the window object is the global scope. This is the highest scope in the scope chain. If we create a new function in the global scope the scope of this function will be chained to the window object:

var msg = "hello world";

function foo(){
    alert(msg);
};

foo();

Now, if you call foo, it'll alert hello world! But how does it know the value of msg, which wasn’t defined in the function body foo? It turns out that if the JavaScript interpreter can’t find a variable in it’s current scope, it’ll go up the scope chain and searches the parent scope until it finds the variable. In our case it finds msg in global scope.

You can also create a scope chain by nesting functions:

function foo(){
    var msg = "hello world";
    function bar(){
        alert(msg);
    };
    bar();
};

foo();

Now, if you call foo, it’ll define bar and execute it immediately afterwards. And as expected it’ll alert hello world.

When a nested function has access to the scope of it’s parent function, it is called a closure. sIFR relies quite heavily on closures. 

 ------------------------------------------------------

ECMA-262把内置对象(built-in object)定义为由ECMAScript实现提供的、独立于宿主环境的所有对象,在ECMAScript程序开始执行时出现。
这意味着开发者不必明确实例化内置对象,它已被实例化了。ECMA-262只定义了两个内置对象,即Global和Math(它们也是本地对象,根据定义,每个内置对象都是本地对象)。

1. Global对象
Global对象是ECMAScript中最特别的对象,因为实际上它根本不存在。如果尝试编写下面的代码,将得到错误:
var pointer = Global;
错误消息显示Global不是对象,但刚才不是说Global是对象吗?没错。这里需要理解的主要概念是,在ECMAScript中,不存在独立的函数,
所有函数都必须是某个对象的方法。本书前面介绍的函数,如isNaN()、isFinite()、parseInt()和parseFloat()等,看起来都像独立的函数。
实际上,它们都是Global对象的方法。而且Global对象的方法不止这些。
       

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值