当前位置:网站首页>Discussion on arrow function of ES6
Discussion on arrow function of ES6
2022-04-23 07:36:00 【flym_】

The difference between arrow function and ordinary function , The essence is whether we understand the arrow function , When I first came into contact with ES6 when , The difference between the arrow function in the impression and the ordinary function is this The direction of is different , A pointer to a window, An instance pointing to the current , Scope . But arrow function is far more than such a knowledge point , So learn the arrow function again :
JavaScript in ,this The value of is specified only when the function is called . Top level non method calls will this As window. ( Be careful : In strict mode , this by undefined instead of window). The arrow function can save the... When the function is created this value , Instead of the value at call time . This is from ts Explanation on the official website .
Arrow function
explain
Arrow function expression The grammar of Function expression More concise , And there's no one of its own this,arguments,super or new.target. These function expressions are more suitable for those places where anonymous functions are needed , And they can't be used as constructors .
Arrowhead function this
1. Arrow functions do not create their own this, It will only inherit from the upper level of its scope chain this. Arrowhead function this Point to... Inherited from the first ordinary function in the outer layer at the time of definition this.
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| Point to... Correctly p example
}, 1000);
}
var p = new Person();
2. If there is no ordinary function outside the arrow function , In a non-strict mode , Default binding this Point to global object , In strict mode this Point to undefined
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log( this.i, this)
}
}
obj.b();
// undefined, Window{...}
obj.c();
// 10, Object {...}
The arrow function doesn't prototype( Prototype ), So the arrow function itself doesn't have this
let obj = () =>{};
console.log(obj .prototype); // undefined
adopt call or apply call , You can't change the arrow function directly this Point to
because Arrow function does not have its own this The pointer , adopt call() or apply() Method to call a function , Only parameters can be passed ( Can't bind this), Their first parameter will be ignored .
var adder = {
base : 1,
add : function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base : 2
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // Output 2
console.log(adder.addThruCall(1)); // Still output 2( instead of 3 )
Arrowhead function arguments, Arrow functions are not bound Arguments object , in other words arguments either
- Be careful : Arrowhead function this When pointing to a normal function , its argumens Inherited from this normal function
function foo() {
console.log(arguments) // { '0': 1, '1': 2 }
return function() {
console.log(arguments[0]) // { '0': 3, '1': 4 }
}
}
foo(1, 2)(3, 4) // 3
rest Parameter gets the remaining parameters of the function , in the majority of cases , Using the remaining parameters is compared to using arguments Better choice of objects .
rest The usage of parameters is relative to arguments The advantages of :
- Arrow function and ordinary function can be used .
- More flexible , The number of receive parameters is completely custom .
- Rest The operator of the parameter is expressed as 3 A little bit …. To be frank , It means “ Put the remaining parameters into an array ”.
let a = (first, ...rest) => {
console.log(first, rest); // 1 [2, 3, 4]
};
a(1, 2, 3, 4);
function foo() {
console.log(arguments) // { '0': 1, '1': 2 }
return () => console.log(arguments[0])
}
foo(1, 2)(3, 4) // 1
Use new The operator
Arrow functions cannot be used as constructors , and new Using it together will throw an error , Because the arrow function doesn't constructor.
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
Use of arrow function , More concise than ordinary functions
Shorter functions and no binding this
1. Make the callback function look more elegant
2. You can omit parentheses when there is only one parameter
3. Function can be omitted when there is only one statement {} and return
4. Arrow functions are anonymous functions , And don't even write function
[8, 6, 7, 9].map(function(item) {
return item;
});
[8, 6, 7, 9].map(item => item;);
Use yield keyword
yield Keywords are usually not used in arrow functions ( Unless it's nested within a function that's allowed ). therefore , Arrow functions cannot be used as generators
Example ( Interview questions )
var id = 'global';
var obj = {
id: 'item',
a: function(){
console.log(this.id);
},
b: () => {
console.log(this.id);
}
};
obj.a(); // 'item'
obj.b(); // 'global'
The above example , object obj Methods a Defined using ordinary functions , When a normal function is called as a method of an object ,this Point to the object it belongs to . therefore ,this.id Namely obj.id, So the output ’item’.
But the way b Is defined using the arrow function , In the arrow function this It is actually inherited from the global execution environment in which it is defined this, So the point to Window object , So the output ’global’.( Pay attention here , Defines the braces for the object {} It is impossible to form a separate execution environment , It is still in the global execution environment !!)
Summary of the article
The arrow function has several points for attention .
(1) In function body this object , Is the object of definition , Instead of using the object .
(2) Can't be used as a constructor , in other words , Not available new command , Otherwise, an error will be thrown .
(3) Not available arguments object , The object does not exist inside the function . If you want to use , It can be used rest Parameters instead of .
(4) Not available yield command , So the arrow function cannot be used as Generator function .
(5) Do not define arrow functions on the outermost layer , At least an ordinary function should be wrapped outside the arrow function .
(6) Arrowhead function this Unexpected points and readability of code .
When to use the arrow function
- In the pure function scenario without complex logic or side effects , for example map,forEach Use in callback .
Precautions in the use of arrow function
1. Returns the literal amount of the object , Remember to wrap the literal value of the object in parentheses :
2. Line break , Arrow functions cannot wrap between arguments and arrows .
3. Parsing order , The analytic order of arrow function is relative || Lean forward
4. In a short form , Just one expression , And append an implicit return value . In the block , Clear must be used return sentence .
var func = () => ({foo: 1});
var func = ()
=> 1;
// SyntaxError: expected expression, got '=>'
callback = callback || (() => {});
var func = (x, y) => { return x + y; };
版权声明
本文为[flym_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230617475870.html
边栏推荐
猜你喜欢

记录一下使用v-print中遇到的问题

枫桥学院开元名庭酒店DMR系统解决方案

How does the public and Private Integrated walkie talkie realize cooperative work under multi-mode communication?

Urban emergency management - urban emergency communication command and dispatching system

免费开源智能充电桩物联网SAAS云平台

可视化之路(十一)matplotlib颜色详解

PC端一次启动多个微信

SDC intelligent communication patrol management system of Nanfang investment building

可视化常见问题解决方案(九)背景颜色问题

可视化常见绘图(五)散点图
随机推荐
C语言的指针符号到底靠近变量类型还是变量名?
免费开源充电桩物联网云平台
go语言:在函数间传递切片
Transformer的pytorch实现
[牛客练习赛68]牛牛的粉丝(矩阵快速幂之循环矩阵优化)
数据分析入门 | kaggle泰坦尼克任务(四)—>数据清洗及特征处理
学习笔记6-几种深度学习卷积神经网络的总结
菜菜的刷题日记 | 蓝桥杯 — 十六进制转八进制(纯手撕版)附进制转换笔记
保洁阿姨都能看懂的中国剩余定理和扩展中国剩余定理
Meishe technology launches professional video editing solution for desktop -- Meiying PC version
可视化常见问题解决方案(九)背景颜色问题
SQL练习第一题
Jiangning hospital DMR system solution
Urban emergency management - urban emergency communication command and dispatching system
各类日期转化的utils
连接orcale
PyTorch 13. Nested functions and closures (dog head)
可视化之路(九)Arrow类详解
记录一个查询兼容性的网站,String.replaceAll()兼容性报错
1D/1D动态规划学习总结