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

不言
Release: 2018-07-16 14:45:25
Original
1910 people have browsed it

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 = [];
Copy after login

is equivalent to

a = a || [];
Copy after login

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

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

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; }() );
Copy after login

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()();
Copy after login

栈顶 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(); // 返回这个函数 }
Copy after login

调用一下这个函数

checkscope(); "local scope"
Copy after login

接着这样执行

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

继续调用函数

checkscope()(); "local scope"
Copy after login

闭包有什么用

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

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

这样子就使用闭包

uniqueInteger(); 0 uniqueInteger(); 1
Copy after login

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

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

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

立即调用的函数

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

额,我大概解释一下这段代码。
首先呢,解释最外层的圆括号,因为如果没有圆括号,则这个是一个赋值语句,将一个匿名函数赋值给变量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; } }; }
Copy after login
var c = count(); var d = count(); undefined
Copy after login

在分别执行一下下

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

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

使用getter和setter完成其闭包

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

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

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

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

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

ee.test is not a function
Copy after login

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

ee.test1 = test1; function test1()
Copy after login

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

ee.test1(); undefined ee.test(); 110 ee.test2(); 112
Copy after login

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

叮 又发现一个莫名奇妙的东东 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; }; }
Copy after login

执行一下

ee.test(); 4443
Copy after login

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

var self = this;
Copy after login

将其值保存进一个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!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!