Ordinary functions and arrow function functions

The difference between arrow function and ordinary function

The arrow function solves the pointing problem in ordinary functions

1. The arrow function is an anonymous function, it cannot be used as a constructor, and new cannot be used

insert image description here
Arrow functions are equivalent to anonymous functions and simplify function definitions. Arrow functions have two formats: one contains only one expression, and even {...} and return are omitted. There is another one that can contain multiple statements, and {...} and return cannot be included at this time.

Cannot be used as a constructor, cannot use new

insert image description here
insert image description here

Second, there is no arrow function arguments. ...can be solved with the spread operator

insert image description here

3. The this of the arrow function always points to the parent context (this of the arrow function depends on the parent context of the definition location, and has nothing to do with the location of use. The ordinary function this points to the object being called)

var a=200;

let obj={
    
    
    a:100,
    fn:function(){
    
       //es5 谁调用,this指向谁
        console.log(this.a);
    },![在这里插入图片描述](https://img-blog.csdnimg.cn/20200929152633364.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzYzODk2OA==,size_16,color_FFFFFF,t_70#pic_center#pic_center)

    foo:()=>{
    
       //  es6箭头函数的this指向父级(obj)上下文。
        console.log(this.a)
    }
}


obj.fn();// 100;  
obj.foo();//200

4. The arrow function cannot directly modify its this point through the call(), apply(), and bind() methods. (call, apply, and bind will ignore the first parameter by default, but parameters can be passed normally)

insert image description here

Five, the arrow function has no prototype attribute

insert image description here

Summarize

The arrow function is created by es6 to solve the problem of this pointing. From its appearance, it is an anonymous function and cannot be used as a constructor, so it cannot be new. Arrow functions do not have arguments, but they can be solved with the spread operator (...). The arrow function this always points to the parent context. If there is no parent context, it points to windows. Arrow functions cannot be directly changed by call(), apply(), or bind() this point, the first parameter will be ignored by default, but parameters can be passed normally, and the arrow function has no prototype attribute.

Guess you like

Origin blog.csdn.net/weixin_50407990/article/details/110091338