[Js] Arrow function

Liao Xuefeng's official website JavaScript study notes

1. Basic form

Arrow functions are equivalent to anonymous functions and simplify the function definition.

x => x * x

Equivalent to

function (x) {
    
    
    return x * x;
}

Other forms:

// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

// 可变参数:
(x, y, ...rest) => {
    
    
    var i, sum = x + y;
    for (i=0; i<rest.length; i++) {
    
    
        sum += rest[i];
    }
    return sum;
}

If you want to return an object:

x => ({
    
     foo: x })

The parentheses cannot be omitted, because there is a syntax conflict with the {…} of the function body, like the following:

// SyntaxError:
x => {
    
     foo: x }

Two, this

There is an obvious difference between arrow functions and anonymous functions : the this inside the arrow function is the lexical scope, which is determined by the context.

The definition of this in 1.js

This is a keyword of the Javascript language. It represents an internal object that is automatically generated when the function is running. It is automatically determined according to the scope in each function and points to the caller .

var obj = {
    
    
    birth: 1990,
    getAge: function () {
    
    
        var b = this.birth; // 1990
        var fn = function () {
    
    
            return new Date().getFullYear() - this.birth; // this指向window或undefined
        };
        return fn();
    }
};

2.

The arrow function completely fixes the direction of this. This always points to the lexical scope, which is the outer caller obj . this points to this inherited from the first ordinary function of the outer layer when it was defined . The this object in the function body is the object when it is defined, and has nothing to do with the object when it is used .

var obj = {
    
    
    birth: 1990,
    getAge: function () {
    
    
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25

Guess you like

Origin blog.csdn.net/qq_45617555/article/details/112491948