当前位置:网站首页>Detailed explanation of arrow function 2021-04-30
Detailed explanation of arrow function 2021-04-30
2022-07-27 00:45:00 【Bug I'll write it】
Arrow function details
List of articles
- Arrow function details
- 1. Basic grammar
- 2. Basic characteristics of arrow function
- (1). Arrow function this Of the parent scope this, Not when called this
- (2). Arrow function cannot be a constructor , Out of commission new
- (3). The arrow function doesn't arguments,caller,callee
- (4). The arrow function passes through call and apply call , Will not change this Point to , Only parameters are passed in
- (5). Arrow functions have no prototype properties
- (6). The arrow function cannot be used as Generator function , Out of commission yield keyword
- (7). When the arrow function returns an object , Add a parenthesis
- (8). The arrow function is in ES6 class The methods declared in are instance methods , Not a prototype method
- (9). The multiple arrow function is a higher-order function , Equivalent to embedded function
- (10). Common arrow function errors
- 3. some this Point to instance of
ES6 A new function has been added to the standard :Arrow Function( Arrow function ).
1. Basic grammar
In general, the definition method of function
var fn1 = function(a, b) {
return a + b
}
function fn2(a, b) {
return a + b
}
Use ES6 Arrow function syntax defines functions , The original function of the “function” Delete the keyword and function name , And use “=>” Connecting parameter lists and function bodies .
var fn1 = (a, b) => {
return a + b
}
(a, b) => {
return a + b
}
When there is only one function parameter , Brackets can be omitted ; But without parameters , Brackets cannot be omitted .
// No arguments
var fn1 = function() {
}
var fn1 = () => {
}
// Single parameter
var fn2 = function(a) {
}
var fn2 = a => {
}
// Multiple parameters
var fn3 = function(a, b) {
}
var fn3 = (a, b) => {
}
// Variable parameters
var fn4 = function(a, b, ...args) {
}
var fn4 = (a, b, ...args) => {
}
Arrow functions are equivalent to anonymous functions , And simplify the function definition . There are two formats for arrow functions , One that contains only one expression , Omit { … } and return. There is also one that can contain multiple statements , At this time, we can't omit { … } and return
() => return 'hello'
(a, b) => a + b
(a) => {
a = a + 1
return a
}
If you return an object , Special attention required , If it's a single expression, return a custom object , If you don't write brackets, you will report an error , Because it's related to the body of a function { … } There are grammatical conflicts .
Be careful , Including braces with parentheses is the definition of an object , Not the body of the function
x => {
key: x} // Report errors
x => ({
key: x}) // correct
Arrow function seems to be a shorthand for anonymous function , But actually , There's an obvious difference between arrow functions and anonymous functions : Inside the arrow function this It's lexical scope , Determined by context .( Lexical scope is the scope defined in the lexical stage . let me put it another way , Lexical scope is determined by where you write variable and block scopes when you write code , So when the lexical analyzer processes code, it keeps the scope the same .
2. Basic characteristics of arrow function
(1). Arrow function this Of the parent scope this, Not when called this
Arrowhead function this Always point to its parent scope , No method can change , Include call,apply,bind.
Of a normal function this Point to the object that called it .
let person = {
name:'jike',
init:function(){
// by body Add a click event , Take a look at this click this What's the difference between properties
document.body.onclick = ()=>{
alert(this.name);//?? this The browser defaults to the object at the time of invocation , Variable ?
}
}
}
person.init();
In the above example ,init yes function, With person.init call , Its internal this Namely person In itself , and onclick Callbacks are arrow functions ,
Inside this, Is the parent scope this, Namely person, Can get name.
let person = {
name:'jike',
init:()=>{
// by body Add a click event , Take a look at this click this What's the difference between properties
document.body.onclick = ()=>{
alert(this.name);//?? this The browser defaults to the object at the time of invocation , Variable ?
}
}
}
person.init();
In the above example ,init Is the arrow function , Inside this For the whole window,onclick Of this That is to say init Functional this, It's also window,
Got this.name for undefined.
(2). Arrow function cannot be a constructor , Out of commission new
The constructor is as follows :
function Person(p){
this.name = p.name;
}
// If you use the arrow function as the constructor , Is the following
var Person = (p) => {
this.name = p.name;
}
because this Must be an object instance , The arrow function has no instance , Here this Point elsewhere , Can't produce person example , stultify oneself .
(3). The arrow function doesn't arguments,caller,callee
The arrow function itself doesn't have arguments, If the arrow function is in a function Inside , It will take the of the external function arguments Take it and use it .
To receive indefinite parameters in the arrow function , You should use rest Parameters … solve .
let B = (b)=>{
console.log(arguments);
}
B(2,92,32,32); // Uncaught ReferenceError: arguments is not defined
let C = (...c) => {
console.log(c);
}
C(3,82,32,11323); // [3, 82, 32, 11323]
(4). The arrow function passes through call and apply call , Will not change this Point to , Only parameters are passed in
let obj2 = {
a: 10,
b: function(n) {
let f = (n) => n + this.a;
return f(n);
},
c: function(n) {
let f = (n) => n + this.a;
let m = {
a: 20
};
return f.call(m,n);
}
};
console.log(obj2.b(1)); // 11
console.log(obj2.c(1)); // 11
(5). Arrow functions have no prototype properties
var a = ()=>{
return 1;
}
function b(){
return 2;
}
console.log(a.prototype); // undefined
console.log(b.prototype); // {constructor: ƒ}
(6). The arrow function cannot be used as Generator function , Out of commission yield keyword
(7). When the arrow function returns an object , Add a parenthesis
var func = () => ({
foo: 1 }); // correct
var func = () => {
foo: 1 }; // error
(8). The arrow function is in ES6 class The methods declared in are instance methods , Not a prototype method
//deom1
class Super{
sayName(){
//do some thing here
}
}
// adopt Super.prototype Access to sayName Method , The method of this formal definition , It's all defined in prototype On
var a = new Super()
var b = new Super()
a.sayName === b.sayName //true
// All instantiated objects share prototypy Upper sayName Method
//demo2
class Super{
sayName =()=>{
//do some thing here
}
}
// adopt Super.prototype Can't access sayName Method , This method is not defined in prototype On
var a = new Super()
var b = new Super()
a.sayName === b.sayName //false
// The instantiated objects have their own sayName Method , Than demo1 Need more memory space
therefore , stay class Try not to use arrow functions to declare methods .
(9). The multiple arrow function is a higher-order function , Equivalent to embedded function
const add = x => y => y + x;
// amount to
function add(x){
return function(y){
return y + x;
};
}
(10). Common arrow function errors
let a = {
foo: 1,
bar: () => console.log(this.foo)
}
a.bar() //undefined
bar Function this Point to the parent scope , and a Object has no scope , therefore this No a, The result is undefined
function A() {
this.foo = 1
}
A.prototype.bar = () => console.log(this.foo)
let a = new A()
a.bar() //undefined
Use the arrow function on the prototype ,this Point to its parent scope , It's not an object a, Therefore, the expected results are not obtained
3. some this Point to instance of
var obj = {
birth: 1990,
getAge: function(){
console.log(new Date().getFullYear() - this.birth); //this Point to obj object
},
}
obj.getAge(); // 29
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = function () {
return new Date().getFullYear() - this.birth; // this Point to window or undefined
};
return fn();
}
};
obj.getAge();// NaN
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this Point to obj object
return fn();
}
};
obj.getAge(); // 29
var obj = {
getAge: () => {
console.log(this); // window
}
};
obj.getAge(); //window
var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this Point to obj object
return fn();
}
};
obj.getAge(); // 29
var obj = {
getAge: () => {
console.log(this); // window
}
};
obj.getAge(); //window
As an attribute of an object ,this The point of is no longer the object itself , The arrow function captures obj{} The environment of this object , And then in this environment this Pointing to window
边栏推荐
- Matlab based medical imaging technology filtering backprojection simulation, including direct backprojection, S-L filtering, R-L filtering, LeWitt filtering
- Use of postman
- 3_Jupyter Notebook, numpy和matplotlib
- Medical data of more than 4000 people has been exposed for 16 years
- 重学JSON.stringify
- 【4.1 质数及线性筛】
- "Syntaxerror: future feature annotations is not defined"
- Leetcode high frequency question: the choice of the inn, how many options to choose accommodation, to ensure that you can find a coffee shop with a minimum consumption of no more than p yuan in the ev
- Mysql常用函数(汇总)
- 输入一串字母 将里面的元音输出希望各位大佬能给指导
猜你喜欢

C language shutdown applet

Resolve Microsoft 365 and Visio conflicts

3_Jupyter Notebook, numpy和matplotlib

Viterbi Viterbi decoding bit error rate simulation, modulation is QPSK, channel is Gaussian white noise

Matlab simulation of image reconstruction using filtered back projection method

Based on the theoretical principle and simulation results of MATLAB spherical decoding, compare 2norm spherical decoding, infinite norm spherical decoding, ML detection

TypeScript(tsconfig.json)

CDs simulation of minimum dominating set based on MATLAB

DOM day_02(7.8)网页制作流程、图片src属性、轮播图、自定义属性、标签栏、输入框事件、勾选操作、访问器语法

Matlab based medical imaging technology filtering backprojection simulation, including direct backprojection, S-L filtering, R-L filtering, LeWitt filtering
随机推荐
Apply with new, delete and malloc, free to free the heap space
Arcgis和Cass实现断面展高程点
Yolo of Darknet_ Forward of layer_ yolo_ Layer comments
[LeetCode] 无重复最长字符串
Torch. correlation function
DOM day_04(7.12)BOM、打开新页面(延迟打开)、地址栏操作、浏览器信息读取、历史操作
【4.9 容斥原理详解】
JSCORE day_03(7.4)
3_Jupyter Notebook, numpy和matplotlib
Matlab simulation of image reconstruction using filtered back projection method
并行MPI程序传递发送消息
[PCB open source sharing] stc32g12k128/stc8h8k64u development board
[Qt]解决中文乱码问题
Friend friend function and singleton mode
动态联编和静态联编、以及多态
【4.10 博弈论详解】
Vector size performance problems
【4.2 约数】
Search engine realizes keyword highlighting
Openharmony quick start