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

Detailed explanation of javascript closure var that=this

小云云
Release: 2018-02-22 15:57:33
Original
3099 people have browsed it

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次
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template