Note: JavaScript Closures

  • Closure

A closure mechanism for the protection of private variables, private scope formed when the function execution, inside the protected private variable from outside interference. Intuitive, that is to form a stack environment is not destroyed.
For closure, when the external function returns, the function can still access the internal function of the external variables.

function f1()
{
    var N = 0; // N是f1函数的局部变量
    function f2() // f2是f1函数的内部函数,是闭包
    {
        N += 1; // 内部函数f2中使用了外部函数f1中的变量N
        console.log(N);
    }
    return f2;
}
var result = f1();
result(); // 输出1
result(); // 输出2
result(); // 输出3
  • A closure is a whole as well as its internal function scope chain. Closures can be defined using real private variables:
function User() {
    var name;
    this.setName = function(value) {
        name = value;
    };
    this.getName = function() {
        return name;
    };
}
var u = new User();
u.setName("Rohmeng");
console.log(u.name); // 输出undefined
console.log(u.getName()); // 输出Rohmeng

U name property is the object of private property, can not be directly accessed using u.name

Guess you like

Origin www.cnblogs.com/rohmeng/p/11032905.html