ECMAScript6-ES6 arrow function: arrow function syntax, this point in arrow function

The ES6 standard adds a new function: Arrow Function.

One, the definition method of the usual function

var fn1 = function(a, b) {
    
    
    return a + b
}
 
function fn2(a, b) {
    
    
    return a + b
}

Second, the definition method of arrow function

Use ES6 arrow function syntax to define the function, delete the "function" keyword and function name of the original function, and use "=>" to connect the parameter list and the function body.

var fn1 = (a, b) => {
    
    
    return a + b
}
 
(a, b) => {
    
    
    return a + b
}

When there is only one function parameter, the parentheses can be omitted; but when there are no parameters, the parentheses cannot be omitted.

// 无参
var fn1 = function() {
    
    }
var fn1 = () => {
    
    }
 
// 单个参数
var fn2 = function(a) {
    
    }
var fn2 = a => {
    
    }
 
// 多个参数
var fn3 = function(a, b) {
    
    }
var fn3 = (a, b) => {
    
    }
 
// 可变参数
var fn4 = function(a, b, ...args) {
    
    }
var fn4 = (a, b, ...args) => {
    
    }

The arrow function is equivalent to an anonymous function and simplifies the function definition. There are two formats for arrow functions:

  • One type contains only one expression, omitting {…} and return.
    () => return 'hello'
    (a, b) => a + b
    
  • There is another type that can contain multiple statements, at this time {…} and return cannot be omitted
    (a) => {
          
          
      a = a + 1
      return a
    }
    

If you return an object, you need to pay special attention. If it is a single expression to return a custom object, an error will be reported if you don't write parentheses, because there is a syntax conflict with the {…} of the function body. Note that using parentheses to enclose the curly braces is the definition of the object, not the body of the function

x => {
    
    key: x} // 报错
x => ({
    
    key: x}) // 正确

Three, this point

1. Non-arrow functions

In a non-arrow function, the direction of this cannot be determined when the function is defined. Only when the function is executed can it be determined who this points to. In fact, the final point of this is the object that calls it.

var Person = {
    
    
	firstName:'Tom',
	lastName:'Lee',
	getFullName:function(){
    
    
		console.log('this01 = ')
		console.log(this)
		var first = this.firstName
		var fn = function(){
    
    
			console.log('this02 = ')
			console.log(this)
			return this.firstName + this.lastName
		}
		return fn()
	}
}
Person.getFullName()

Print result:

this01 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
this02 = Window {
    
    0: global, window: Window, self: Window, document: document, name: "", location: Location,}
NaN

2. Arrow function

Arrow function seems to be a shorthand for anonymous function, but in fact, there is an obvious difference between arrow function and anonymous function: this inside arrow function is lexical scope, which is determined by context . (The lexical scope is the scope defined in the lexical stage. In other words, the lexical scope is determined by where you write the variable and block scope when you write the code , so when the lexical analyzer processes the code, it will keep The scope remains unchanged.)

Now, the arrow function completely fixes the pointing of this, this always points to the lexical scope, which is the outer caller Person

var Person = {
    
    
	firstName:'Tom',
	lastName:'Lee',
	getFullName:function(){
    
    
		console.log('this01 = ')
		console.log(this)
		var first = this.firstName
		var fn = () => {
    
    
			console.log('this02 = ')
			console.log(this)
			return this.firstName + this.lastName
		}
		return fn()
	}
}
Person.getFullName()

Print result:

this01 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
this02 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
"TomLee"

Fourth, the drawbacks of arrow functions

Every Function object in JavaScript has an apply() method and a call() method

  • apply calls a method of an object and replaces the current object with another object. For example: B.apply(A, arguments); that is, object A calls the method of object B. func.apply(thisArg, [argsArray])
  • call calls a method of an object, replacing the current object with another object. For example: B.call(A, args1,args2); that is, object A calls the method of object B. func.call(thisArg, arg1, arg2, …)

Since this is bound to the lexical scope in the arrow function, when the arrow function is called with call() or apply(), this cannot be bound, that is, the first parameter passed in is ignored

1. Non-arrow functions

var Person = {
    
    
	firstName:'Tom',
	lastName:'Lee',
	getFullName:function(firstName){
    
    
		console.log('this01 = ')
		console.log(this)
		var first = this.firstName
		var fn = function(f){
    
    
			console.log('this02 = ')
			console.log(this)
			return f + this.lastName
		}
		return fn.call({
    
    firstName:'hh'},firstName)
	}
}
Person.getFullName('hi')

Print result:

this01 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
this02 = {
    
    firstName: "hh"}
"hiundefined"

2. Arrow function

var Person = {
    
    
	firstName:'Tom',
	lastName:'Lee',
	getFullName:function(firstName){
    
    
		console.log('this01 = ')
		console.log(this)
		var first = this.firstName
		var fn = (f) => {
    
    
			console.log('this02 = ')
			console.log(this)
			return f + this.lastName
		}
		return fn.call({
    
    firstName:'hh'},firstName)
	}
}
Person.getFullName('hi')

Print result:

this01 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
this02 = {
    
    firstName: "Tom", lastName: "Lee", getFullName: ƒ}
"hiLee"

After using the arrow function, the previous hack is no longer needed, var that = this. But you can't use ES6 arrow functions blindly.

Five, summary

  • Similar to anonymous functions, used in some cases, can reduce the amount of code
  • The code is concise, this is defined in advance
  • The code is too concise, making it difficult to read
  • This is defined in advance, which makes it impossible to use js to perform some operations that seem very normal in ES5 (if you use the arrow function, you cannot get the currently clicked element in the callback function that listens to the click event. For details, see "Use Arrows Correctly" Functions-when should not use ES6 arrow functions"
  • In general, the arrow function is just a shorthand for a function. It has its pros and cons. It can be used or not. It depends on your mood. Of course, you have to use it correctly.



Reference materials:
ES6 new features arrow function syntax, how to use arrow functions correctly

Guess you like

Origin blog.csdn.net/u013250861/article/details/113622275