JavaScript 闭包

JavaScript About 459 words

含义

函数可以使用函数之外定义的变量。

普通闭包

var username = 'Tom';

function sayHi() {
    alert("Hello " + username);
}

sayHi();

函数嵌套闭包

var iBaseNum = 10;

function addNum(iNum1, iNum2) {
  function doAdd() {
    return iNum1 + iNum2 + iBaseNum;
  }
  return doAdd();
}

console.log(addNum(1, 2));

匿名闭包

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

console.log(add()); // 1
console.log(add()); // 2
console.log(add()); // 3
Views: 1,772 · Posted: 2021-06-05

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh