Skip to content

Latest commit

 

History

History
77 lines (61 loc) · 1.29 KB

3.5.1-自由变量和遮蔽.md

File metadata and controls

77 lines (61 loc) · 1.29 KB
  1. 自由变量 hotfix

  • 自由变量与闭包的关系
  • 自由变量的概念
  • 高阶函数的概念
  • 被捕获的变量

Example:

function makeAdded(CAPTURED) {
  return function(free) {
    return free + CAPTURED;
  };
}

var add10 = makeAdded(10);
add10(1);

被捕获的变量类型,也包括函数

function averageDamp() {
  return function(n) {
    // FIXME: where does average function define?
    return average([n, FUN(n)]);
  };
}

var averageSq = averageDamp(function(n) {return n * n});
  1. 遮蔽(Shadowing)

变量x在某一作用域内声明,然后另外一个同名变量再声明,变量遮蔽。

var name = 'Tom';
var name = 'Jerry';
name; // => Jerry

函数参数的遮蔽:

var shadowed = 0;

function argShadow(shadowed) {
  return ['Value is:', shadowed].join('');
}

argShadow(108);

离得最近的变量绑定优先级最高。

var shadowed = 0;

function argShadow(shadowed) {
  var shadowed = 1000;
  return ['Value is:', shadowed].join('');
}

argShadow(108);

遮蔽变量在闭包内:

function captureShadow(SHADOWED) {
  return function(SHADOWED) {
    return SHADOWED + 1;
  }
}

var closureShadow = captureShadow(1);
closureShadow(2); // => 3