当前位置:网站首页>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
边栏推荐
猜你喜欢

13_ Ensemble learning and random forests

c语言 static运用,灵活改变生命周期,让你写代码如鱼得水

Two or three things about redis

Use of postman

The company gave how to use the IP address (detailed version)

MySql

Web middleware log analysis script 2.0 (shell script)

Two methods of automated testing XSS vulnerabilities using burpsuite

6_梯度下降法(Gradient Descent)

【 Educational Codeforces Round 132 (Rated for Div. 2) A·B·C】
随机推荐
postman的使用
5_线性回归(Linear Regression)
8_ Polynomial regression and model generalization
【4.9 容斥原理详解】
【Codeforces Round #807 (Div 2.) A·B·C】
c语言 比大小的多种描述,不要只拘泥于一种写法
[PCB open source sharing] stc8a8k64d4 development board
我的第一篇博客-迷茫的大三人
8_多项式回归及模型泛化(Polynomial Regression and Model Generalization)
[Qt]元对象系统
JSCORE day_04(7.5)
10_ Evaluate classification
[3. Basic search and first knowledge of graph theory]
[interview: concurrent Article 16: multithreading: detailed explanation of wait/notify] principle and wrong usage (false wake-up, etc.)
关于Redis问题的二三事
On the expression of thymeleaf
[acwing game 61]
裁剪tif影像
Oracle data guard service, process and protection mode
[Qt]容器类、迭代器、foreach关键字