JavaScript的Function Scope and Lexical Scope

原贴地址:http://pierrespring.com/2010/05/11/function-scope-and-lexical-scoping/

个人觉得写得不错,简单地搬运,如有错误,请指正。

 

Wikipedia defines Scope as follows:

  Tipically, scope is used to define the extent of information hiding--that is, the visibility or accessibility of

  variables from diefferent parts of the program.

  作用域是用来定义信息隐藏的深度--程序中,其它地方对某个部分中的变量的可访问性。

In JavaScript we have Function Scope and Lexical Scope.

Function Scope means that any variable which is defined within a function is visible within that entire function.

Block Scope, in which a variable scope is limited by the block a variable is declared in.

A block is usual {curly brace} or loop variables.

Function Scope 是指,任何在函数内部定义的变量是对整个函数都可见的。

Think of a simple for(;;){} loop:

  var i = 1; // it's global variable.

  for ( var i = 0 ; i< 10; i++) {

    console.log(i); // start from 0

  }

  console.log(i); // output 10;

  //--------->block scope: 1

  //--------->function scope:10

Lexical Scoping defines how variable names are resolved in nested functions.

The Lexical Scoping is called as Static Scoping or Closure. It means that the scope of an inner function contains the scope of a parent fucntion.

 

var baz;

var outer_var = "I'm outer var";

(function() {  

  baz = function() {   

    var inner_var = "I'm inner var";

    console.log(foo * bar);  

  };

  var foo = 10;  

  var bar = 2;  

  console.log(outer_var);

  console.log(inner_var);

})();

console.log(inner_var); //error

console.log(outer_var); // "I'm outer var"

console.log(baz()); //20

Lexical Scoping: The scope of an inner function contains the scope of a parent function, even if the parent function has returned.

In JavaScript functions are first class objects.That means that you can pass functions as arguments or they can be returned from a function. They can also be assigned to a variable or stored in an object.

var annoy = function (total) {

  var inner_funct = function (sum) {

    total += sum;

    console.log(total);

  }

  return inner_funct;

}(1); //total  starts from 1

annoy(2); //3

annoy(4);//7

 

转载于:https://www.cnblogs.com/Yaxian/p/4510030.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值