[JS] The difference between arrow functions and arrow functions and ordinary functions [detailed explanation]

Arrow function:

definition:

通俗的理解 箭头函数就是return函数

Definition:
ES6 allows the use of "arrows" (=>) to define functions
Basic format:

() => {
    
    }
eg:
let xx = ()=> 555
console.log( xx() )
就等同于:
function xx2() {
	return 666;
}
console.log( xx2())

The syntax of an arrow function:

  1. () to define parameters, if there is only one parameter, you don’t need to write parentheses (if there are many parameters, you can use "," to separate them in parentheses);
  2. Write the function body in {}, if there is only a return value in the function body, you don’t need to write return;

The difference between arrow functions and ordinary functions:

For example:
SLT Exclusive
it is obviously possible to output
and then improve it:

let obj = {
    
    
	name = "小明",
	age = 2,
	sayName(){
    
    
		//console(`我是${this.name}`)
		setTimeout(function(){
    
    
			console.log("我是" + this.name)
		},500)
	}
}
obj.sayName();	

Do you think "I am Xiao Ming" will be output after 0.5s this time?
Like it if you think it's okay,
forward it if you don't think it's okay

Let's look at the effect:
SLT Exclusive
obviously there is no output

Then we:
SLT Exclusive
where this refers to the window object, and the window object is the global object

This is a method within a method.
The this in the external method refers to Xiaoming.
The output of the method inside is the window object.

If it is es5,
SLT Exclusive
we can use this method (pass value) to get Xiaoming's name

If you use an arrow function, you can use this:
SLT Exclusive

So why can you use arrow functions when you can use ordinary functions?

The difference between the arrow function and the ordinary function is obtained:

  1. This points to different:
    ordinary functions, whoever calls this this points to who
    Arrow function, where the function is defined, this points to who
    (it can be understood that the internal arrow function will not change the object this points to, this still points to the scope of the outer function )

Guess you like

Origin blog.csdn.net/SLT1210/article/details/124497651