search
HomeWeb Front-endJS TutorialUnderstanding of actual parameters, formal parameters and closures of js functions

This article mainly introduces the understanding of actual parameters, formal parameters and closures of js functions. It has certain reference value. Now I share it with you. Friends in need can refer to it

Selecting formal parameters

if(a === undefined) a = [];

is equivalent to

a = a || [];

These two sentences are completely equivalent, except that the latter needs to declare a in advance
If the parameters are not passed in, the rest will be filled in undefined
Optional formal parameters: Use the comment /optional/ to emphasize that the parameters are optional, and put them at the end, otherwise null or undefined will be used as placeholders to pass Enter

Variable length actual parameter list

callee and caller

callee refers to the function currently being executed
caller refers to the function currently executing the function

Use object properties as actual parameters

>
> function e(o){
...   return o.Object;
... }
undefined
> e;
[Function: e]
> var a = {Object:33};
undefined
> e(a);
33
>

Function as value

Function can be passed into another function as value

Custom function properties

Function attributes can be customized

o.a = 3;
function o() {
  return o.a;
}

Understanding of actual parameters, formal parameters and closures of js functions

Function as a namespace

Variables declared in the function are visible throughout the function body (including within nested functions), are not visible outside the function. Variables not declared within any function are global variables. It is visible throughout the js program. In js, you cannot declare variables that are only visible within a code block. So it is often simple to define a function to use as a temporary namespace. Variables defined within this namespace will not pollute the global namespace.
It is precisely because if variables are defined globally, variable pollution will occur, and global variables will be polluted (well, this is a pitfall of dynamic languages), resulting in some unknown errors. Therefore, placing the variables in the function and calling it will pollute its global space and cause variable conflicts (especially in the browser environment, it is easy to cause various unknown errors, so it must be like this Do)

Call the function directly after defining the function

(
  function() {
    return 333;
  }()
);

It is necessary to add (), because if you do not add (), the js interpreter will think it is a function declaration, and the function will be declared as a function To explain, the js interpreter does not allow the creation of an anonymous function declaration, so an error will be reported.
Adding () becomes a function expression, and the js interpreter runs to create an anonymous function expression

Closure

Finally reaches the closure. (Serious point Σ( ° △ °|||)︴)
(This is the most difficult part, the foundation of functional programming, and the most critical part of whether you can learn js well... Of course, es6 There is also an annoying arrow function)
Closure is an important basis for its functional programming
Like other languages, js adopts lexical scope, that is, the execution of the function depends on the scope of the variable. The domain is determined when the function is defined, not when it is called.
That is, the internal state of the function object of js not only contains the code logic of the function, but also must refer to the current scope chain (the scope of the variable is downward) Passed, the scope chain of the variable is searched upward when searching, until the top of the function) Function objects can be related to each other through the scope chain, Variables inside the function body can be saved in the function scope , that is, closure

is a very old term, which means that function variables can be hidden within the scope chain, so it seems that the function wraps the variables.

How to define scope chain

The scope chain is a list of objects. Every time a js function is called, a new object will be created to save its local variables. Add this object In the scope chain, if the function returns, the bound object will be deleted from the scope chain. If there is no nested function, and there is no reference to the bound object, it will be garbage collected by the js interpreter. The mechanism's irregular recycling is irregular and does not delete it immediately when it is not fully referenced. If nested functions are defined, each nested function corresponds to a scope chain, and this scope chain points to a variable. The bound object. If these nested function objects are saved in the outer function, they will also be garbage collected like the variable binding object they point to, if the function defines the nested function and returns it as a return value, or If stored in a certain attribute, there will be an external reference pointing to this nested function, that is, it will not be treated as garbage collection, and the object bound to its variable will not be treated as garbage collection.

After the function is executed, the relevant scope chain will not be deleted. The deletion operation will only be performed when there is no longer a reference.

Understanding of actual parameters, formal parameters and closures of js functions

About the stack Description

Original stack
Top window
Execute the following js script

function a() {
  function f() {
    return 333;
  }
  return f;
}
a()();

栈顶 a → window
开始调用,执行到return
发现需要调用f
继续加栈
栈顶 f → a → window
执行完f弹出f
继续执行a,执行完毕弹出a
最后全部执行完毕弹出window

算了文字解释太无力,直接上代码

var scope = "global scope"; // 一个全局变量
function checkscope() 
{
  
  var scope = "local scope";  // 定义一个局部变量
  
  function f() 
  {
    return scope; // 返回变量作用域中的scope的值
  }
  
  return f(); // 返回这个函数
}

调用一下这个函数

checkscope();
"local scope"

接着这样执行

var scope = "global scope"; // 一个全局变量
function checkscope() 
{
  
  var scope = "local scope";  // 定义一个局部变量
  
  function f() 
  {
    return scope; // 返回变量作用域中的scope的值
  }
  
  return f; // 返回这个函数
}

继续调用函数

checkscope()();
"local scope"

闭包有什么用

先看一个函数uniqueInteger()使用这个函数能够跟踪上次的返回值

var uniqueInteger = (
  function() {
    var count = 0;
    return function() {return count++}
  }()
);

这样子就使用闭包

uniqueInteger();
0
uniqueInteger();
1

每次返回是其上一次的值,并随便直接将值加1
至于为什么要这样写,如果不使用闭包,那么恶意代码就可以随便的将计数器重置了。。

uniqueInteger.count = 0;
function uniqueInteger() {
  return uniqueInteger.count++;
}

类似这样的,完全可以做到直接通过赋值,将其count的值重置。
而如果使用闭包,没有办法进行修改,为私有状态,也不会导致其一个页面内变量的冲突,或者是其覆盖。

立即调用的函数

var a = (function c(){
  var a = 1;
  a++;
  console.log('已经执行');
  return function b(){return a++};
}())

额,我大概解释一下这段代码。
首先呢,解释最外层的圆括号,因为如果没有圆括号,则这个是一个赋值语句,将一个匿名函数赋值给变量a,实际上是在内存中完成了栈中变量a指向匿名函数存储的空间的地址,如果有圆括号,实际上是告诉js解释器这是一个语句,需要js执行,消除了其function带来的影响。(ps;貌似火狐上不加也可以,也可以正常的运行)执行和引用的关系下方有。
然后呢,最后的圆括号,代表着其执行这个函数,因为js解析器将()解析为调用前方的函数名称,类似于运算符吧。但是实际上并不是运算符,因为能往其内传值,注意,这点是将其执行的结果保存在堆中,并完成其指向
其后,当直接输入a;,实际上执行并完成了一次调用,其返回值为函数b,将函数b完成一次引用,即变量a引用函数b,由于其存在引用关系,即栈中变量a保存的为其函数a的返回结果,(因为其不是不是对象,如果写a()()表示将函数a调用后返回的对象保存在栈中,然后将栈中的内容再次调用,由于是保存,并不存在其应用关系,所以执行完毕后直接垃圾回收)由于其保存的是函数b的作用域链,而函数b的作用域链是继承自函数a的作用域链,但是由于函数a的作用域链并没有引用导致其执行完后被垃圾回收(当不在有变量指向的时候)。所以呢,函数其值是在函数b中进行保存,如果修改函数c此时函数c并不会影响到函数b中的保存,因为其函数c的变量列表已被销毁,
最后,继续讨论起嵌套函数的引用,由于其父函数已被销毁,但是嵌套函数被引用,(注意:因为其父已经没有,所以是另开辟一块新的堆空间,用于存储其函数c的返回结果,注意是返回结果,而不是函数b)此时另外指定变量保存其结果,无论指定多少个变量保存其结果,都是新的空间的执行,没有任何的干扰,详细了解看下面,继续讨论

  1. ps;如果是()()则代表其会被其垃圾回收

  2. ps 还需要注意一点点的是由于其引用的是result的值,并不是其

最后,这样就能完成其变量保存在函数中,貌似叫做记忆?

所以呢,借助堆和栈就很好的能理解了闭包

再继续看代码

function count() {
  var n = 0;
  return {
    count: function() { return n++; },
    reset: function() { n = 0; }
  };
}
var c = count(); var d = count();
undefined

在分别执行一下下

c.count();
0
d.count();
0
c.count();
1
d.count();
1
c.reset();
undefined
c.count();
0
d.count();
2

这一点体现了其互不影响性,表明其由于其父被回收,导致其子分别开创了一块在堆中新的内存空间,并完成其指向,互相不干扰。
其作用域链互不干扰

使用getter和setter完成其闭包

function count(n) {
  return {
    get count() { return n++; },
    set count(m) { 
      if ( m >= n)
        n = m;
      else
        throw new Error( '请输入一个正确的值' );
    },
  };
}

这个就不用解释啦,很简单啦

同一个作用域链中定义两个闭包

function test1() {
  val = value = 111;
  this.test = function() { return value - 1; };
  this.test2 = function() { return value + 1; };
  
}

这同样是两个作用链域
不过这样写需要先执行其o.test1(),因为其方法在其函数内部,必须先执行一下,完成其方法的添加,否则会报错,

ee.test is not a function

提示找不到这个方法,
因为执行

ee.test1 = test1;
function test1()

只是简单的进行赋值,并不能进行查看,所以导致其无法使用
所以嘛,要先执行一遍,让其方法添加进去

ee.test1();
undefined
ee.test();
110
ee.test2();
112

这就是两个闭包,这两个闭包互相平行,同时继承于其父,但是又不受其父影响,很神奇吧,(@ο@)

叮 又发现一个莫名奇妙的东东 https://us.leancloud.cn 貌似目前水平能看懂一些了

关于this的问题

this在父闭包显示的即为使用该方法的对象。
但是子就不一定了。

function test1() {
  val = value = 111;
  this.test = function() { return this.x - 1; };
  this.test2 = function() { return this.x + 1; };
}

执行一下

ee.test();
4443

这就尴尬了。
好吧。只能说是一般不这样用
一般这样写

var self = this;

将其值保存进一个self中

相关推荐:

js的函数声明和函数表达式的分析

如何使用JS求数组差集的方法

The above is the detailed content of Understanding of actual parameters, formal parameters and closures of js functions. 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.