Home  >  Article  >  Web Front-end  >  Detailed explanation of javascript closure var that=this

Detailed explanation of javascript closure var that=this

小云云
小云云Original
2018-02-22 15:57:333016browse

Quick Overview

var f1  = function(){
    var a = 999;
    nAdd = function(){n+=1}    //没有var,nAdd是全局变量
    f2 = function(){
        alert(a)
    }
    return f2;
}
var result = f1();
result();    //999
nAdd();        //相当于一个setter,可以在函数外部操作函数内部变量的值
result();    //1000,f2()被执行了2次

The concept of closure

Function within a function

The purpose of closure

You can read variables inside the function
Always keep the variables of the parent function in memory
Note: If you want to keep the variable values ​​of the parent function unchanged, you need to use the parent function as an object

//父函数作对象
var name = 'The Window';
var object = {
    name : 'The Object',
    getName : function(){
        return function(){
            return this.name
        }
    }
}

alert(object.getName()())    //The Window

var that = this;

var _name = 'The Window';
var object = {
    _name : 'The Object',    //_name 下划线表示私有变量
    getName : function(){
        var that = this;
        return function(){
            return that._name;
        }
    }
}

alert(object.getName()())    //The Object

that=this / _this=this


##Learn Javascript Closure (Closure) (Ruan Yifeng)

Related recommendations:

Detailed introduction to JavaScript closures

Simple application of JavaScript closure examples

javascriptWhat is the closure? How to use javascript closure?

The above is the detailed content of Detailed explanation of javascript closure var that=this. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn