Home Web Front-end JS Tutorial JavaScript Basics (6) Function Expression Closure_Javascript Skills

JavaScript Basics (6) Function Expression Closure_Javascript Skills

May 16, 2016 pm 03:26 PM

In fact, the main reason why js supports function closures is because js needs functions to be able to save data. The saved data here is that only the values ​​of variables within the function will be saved after the function ends. As for why js needs to be able to save data within a function, that is that js is a functional language. Saving data within functions is a hallmark of functional languages.

Review the three methods of defining functions introduced earlier

functiosu(numnumreturnunum//Function declaration syntax definition
vasufunction(numnum)returnunum}//Function expression definition
vasuneFunction("num""num""returnunum")//Functio constructor

Before analyzing closures, let’s take a look at common mistakes in defining and calling functions.

Example 1:

sayHi(); //错误:函数还不存在
var sayHi = function () {
  alert("test");
};
Copy after login

Example 2:

if (true) {
  function sayHi() {
    alert("1");
  }
} else {
  function sayHi() {
    alert("2");
  }
}
sayHi();//打印结果并不是我们想要的
Copy after login

Example 3:

var fun1 = function fun2() {
  alert("test");
}
fun2();//错误:函数还不存在
Copy after login

In Example 1, we cannot call the function before defining it using function declarative syntax. Solution:

1. If you use a function expression to define a function, it needs to be called after the expression is defined.

var sayHi = function () {
  alert("test");
};
sayHi()
Copy after login

2. Use function declarations. (Here the browser engine will promote function declarations and read the function declaration before all code is executed)

sayHi(); 
function sayHi () {
  alert("test");
};
Copy after login

In Example 2, our expected result should be to print 1, but the actual result is to print 2.

if (true) {
  function sayHi() {
   alert("1");
  }
  } else {
  function sayHi() {
   alert("2");
  }
}
sayHi();//打印结果并不是我们想要的
Copy after login

Why is this happening? Because of function declaration promotion, the browser will not judge the if condition during pre-parsing, and directly overwrites the first one when parsing the second function definition.

Solution:

var sayHi;
if (true) {
  sayHi = function () {
   alert("1");
  }
  } else {
  sayHi = function () {
   alert("2");
  }
}
sayHi();
Copy after login

In Example 3, we found that we can only use fun1() to call, but not fun2().

From my own understanding, I don’t know the real reason. No information found.

Because 1: function fun3() { }; is equivalent to var fun3 = function fun3() { }; as shown in the figure:

So you can only use fun1() to call, but not fun2().

Actually, I still have questions here? If anyone knows, please let me know.

Since fun2 cannot be called from outside, why can it be called from inside the function? Although I still can't get fun1 in the debugger.

Okay, let’s warm up with the three questions above. Let’s continue with today’s topic of “closures”.

1. What is closure?

Definition: It is a function that has access to variables in the scope of another function

Let’s start with an example function:

Example 1:

function fun() {
  var a = "张三";
}
fun();//在我们执行完后,变量a就被标记为销毁了
Copy after login

Example 2:

function fun() {
  var a = "张三";
  return function () {
    alert("test");
  }
}
var f = fun();//同样,在我们执行完后,变量a就被标记为销毁了
Copy after login

Example 3:

function fun() {
  var a = "张三";
  return function () {
    alert(a);
  }
}
var f = fun();//【现在情况发生变化了,如果a被销毁,显然f被调用的话就不能访问到变量a的值了】
f();//【然后变量a的值正常的被访问到了】
//这就是闭包,当函数A 返回的函数B 里面使用到了函数A的变量,那么函数B就使用了闭包。
示例:
function fun() {
  var a = "张三";
  return function () {
   alert(a);
  }
}
var f = fun();//【现在情况发生变化了,如果a被销毁,显然f被调用的话就不能访问到变量a的值了】
f();//【然后变量a的值正常的被访问到了】
Copy after login

Obviously, misuse of closures will increase memory usage. So try not to use closures unless there are special circumstances. If used, remember to manually set a null reference so that the memory can be recycled f = null ;

Illustration: (Students who don’t understand scope chain, please read the previous article Scope and Scope Chain first)

2. What is an anonymous function? (Just explaining the concept)

For example: (that is, a function without a name)

About the weird phenomenon of this when the return value of the function in the object is an anonymous function

Before explaining, please clear your head first and don’t get more confused as you read. If you are confused, just ignore the following.

var name1 = "张三";
var obj = {
  name1: "李四",      
  fun2: function () {
    alert(this.name1);
  },
  fun3: function () {
    return function () {
      alert(this.name1);
    }
  }
}
Copy after login

obj.fun2();//The printing result "李思" is as expected.
obj.fun3()();//Because what is returned here is a function, we need to add a pair of () to call it. The printed result is "Zhang San", which is unexpected.
//It’s really confusing. What does this point to the overall situation?
We said before that "whichever object clicks the method, this is the object", then our obj.fun3()() prints "Zhang San", which means this executes the global scope.

We may understand why by looking at the example below.

var name1 = "张三";
var obj = {
  name1: "李四",      
  fun2: function () {
    alert(this.name1);
  },
  fun3: function () {
    return function () {
      alert(this.name1);
    }
  }
}    
//obj.fun3()();
var obj2 = {};
obj2.name1 = "test";
obj2.fun = obj.fun3();
obj2.fun();//打印结果"test",再次证明了“哪个对象点出来的方法,this就是哪个对象”.
var name1 = "张三";
var obj = {
  name1: "李四",
  fun2: function () {
   alert(this.name1);
  },
  fun3: function () {
    return function () {
     alert(this.name1);
    }
  }
}
//obj.fun3()();
var obj2 = {};
obj2.name1 = "test";
obj2.fun = obj.fun3();
obj2.fun();//打印结果"test",再次证明了“哪个对象点出来的方法,this就是哪个对象”.
Copy after login

我們來分解下 obj.fun3()() 先是  obj.fun3() 回傳一個匿名函數到了window作用域,然後接著呼叫this就指向了window了。 ( 感覺解釋有點勉強,也不知道對不,暫時自己先是這麼理解的 )

閉包形成的原因:記憶體釋放問題

一般,當函數執行完畢後,局部活動物件會被銷毀,記憶體中僅保存全域作用域,但閉包的情況是不一樣的。

閉包的活動物件依然會保存在記憶體中,於是像上例中,函數呼叫返回後,變數i是屬於活動物件裡面的,就是說其棧區還沒釋放,但你呼叫c()的時候i變數保存的作用域鏈從b()->a()->全域去尋找作用域var i宣告所在,然後找到了var i=1;然後在閉包內++i;結果,最後輸出的值就是2了;

以上所述是小編給大家分享的JavaScript基礎篇(6)之函數表達式閉包,希望大家喜歡。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles