Js Closure

  • 72
  • 0
  • Js
  • 2020-01-12

閉包

函式以及該函式被宣告時所在的作用域環境(lexical environment)的組合

函式工廠

私有方法

當變數於函式內使用完畢時,記憶體會釋放(chorme F12 memory 測試),但於父子函式內的變數因作用域的關係做關連於存在記憶體上,而無消除

function init() {
  var name = "Mozilla"; // name 是個由 init 建立的局部變數
  function displayName() { // displayName() 是內部函式,一個閉包
    alert(name); // 使用了父函式宣告的變數
  }
  displayName();
}
init();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

函式工廠

function getname(role)

{

var roles = role || 'person';  //參數無給值則設預設值

return function (name) { //工廠方法來角色與名稱合併

 return roles + name;

}}

var test = getname(man);

console.log(test('peter'));  show manpeter

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

私有方法 

function getname(role)

{

var roles = role || 'person';  //參數無給值則設預設值

return {  //物件方式,定義函式

BoyName : function (name ){

return Boy + name;

},

GirlName : function (name ){

return Girl+ name;

},

}

}

var test = getname(man);

console.log(test.BoyName('peter')); //因不同的方法,做不同的演算

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ref :https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Closures