ES6: arrow function and keyword this

Time:2021-9-3

Arrow function

ES6 allows you to define functions using “arrows” (= >). It not only simplifies the code, but also solves the problem of this pointing in Es5. In the arrow function in ES6, this always points to the object at the time of definition rather than the object at the time of use. For example:

let f = v => v;
//Equivalent to
let f = function (v) {
 return v;
};

If the arrow function does not require parameters or requires more than one parameter, a parenthesis is used to represent the parameter part. For example:

let f = () => 5;

//Equivalent to

let f = function () { return 5 };

  
let sum = (num1, num2) => num1 + num2;

//Equivalent to

let sum = function(num1, num2) {

    return num1 + num2;
};

If the code block of the arrow function has more than one statement, enclose them in braces and return them with the return statement. For example:

let sum = (num1, num2) => { return num1 + num2; }

The arrow function makes the expression more concise. For example:

const isEven = n => n % 2 == 0;

const square = n => n \* n;

The above code only uses two lines to define two simple tool functions. If the arrow function is not used, it may occupy multiple lines, and it is not as eye-catching as it is now.

One use of the arrow function is to simplify the callback function.

//Normal function writing

[1,2,3].map(function (x) {

 return x * x;});

//Arrow function writing

[1,2,3].map(x => x * x);



//Normal function writing

var result = values.sort(function (a, b) {

 return a - b;});

//Arrow function writing

var result = values.sort((a, b) => a - b);

There are several points to note in the use of arrow functions.

(1) The this object in the function body is the object where it is defined, not the object where it is used.

(2) It cannot be used as a constructor, that is, it cannot use the new command, otherwise an error will be thrown.

(3) You cannot use the arguments object, which does not exist in the function body.

For example:

let handler = {

    id: '123456',
    init: function() {

        document.addEventListener('click',event => this.doSomething(event.type), false);

    },
    doSomething: function(type) {

        console.log('Handling ' + type  + ' for ' + this.id);

    }
  };

In the init method of the above code, if you use an ordinary function function, this should be the document itself. After using the arrow function, make this in the arrow function always point to the handler object;
This in dosomething refers to the object handler where dosomething runs.

This keyword

This can be used in constructors to represent instance objects. In addition, this can also be used in other occasions. But no matter what occasion, this has one thing in common: it always returns an object. In short, this is the object where the “current” property or method is located.

This is mainly used in the following occasions

(1) Global environment

The global environment uses this, which refers to the top-level object window.

this === window // true
function f() {
    console.log(this === window);
}
f() // true

Note: in strict mode, this in ordinary functions is equal to undefined

(2) Constructor

This in the constructor refers to the instance object

function Person(p) {

   this.p = p;
   Console.log (this) // person {P: "test this point"}
 };

 var obj = new Person()

As can be seen from the print result, this in the above code points to the person instance

(3) Object method

If the method of an object contains this, the point of this is the object where the method runs.

var person = {

    Name: 'Zhang San',

    describe: function () {

        Return 'Name:' + this. Name;

    }
 };

Person. Describe() // "Name: Zhang San"

In the above code, this. Name represents the object where the name attribute is located. Because this.name is invoked in the describe method, and the describe method’s current object is person, so this points to person, this.name is person.name.

(4) This in anonymous function
If an anonymous function appears inside the method, the object pointed to by this in the anonymous function is uncertain, for example:

var dogs={

    Name: "Xiaohei",
    Age: "1 year old",
    voice:function(){

        console.log(this.name);

        setTimeout(function(){

            console.log(this);// Window is returned

            console.log(this.name);// There is no return value because the name here is a non-existent attribute

            //The solution is console.log (dogs. Name);

        },1000);

    }

}

dogs.voice();

Change this point

1. Use the arrow function
2. In the function, if you want to call the method outside the method inside the event in the method, you can declare a variable outside, let that = this;
For example:

function a(){
    let that=this;
    function b(){
        console.log(that)
    }
    b();
}

3. Use bind, call, or apply methods to change the direction of this;
Bind is the method of ES6, which changes this of the new function;
Call and apply are the methods of Es5:
Call changes this of the original function. Its first parameter is the object pointed to by the changed this, and the remaining parameters are assigned to the formal parameters of the original function in turn;
Apply also changes this of the original function. Its first parameter is also the object pointed to by the changed this. The second parameter is an array, and the values in the array are assigned to the formal parameters of the original function in turn
For example:

//Declare a box function globally and use the bind method to change this point from window to box
function box(){
    console.log(this);//[object global]
}
box();
let res=box.bind(box);
res();

//Bind: bind array

function box2(a,b){
    console.log(this);//1,2
}
let arr=[1,2];
let res2=box2.bind(arr);
res2(...arr);

//Bind: bind object

function objs(o){
    console.log(this);//{  o: 'object'}
}
Let obj = {o: "object"};
let res3=objs.bind(obj);
res3(obj.o);

//es5:call

function box4(aa,bb){
    console.log(this);//[ 1111 ]
}

let ccc=[1111];
box4.call(ccc,10,12);

//es5:apply

function box5(cc,dd){
    console.log(this);//{ a: "Hello"}
}
Var obj = {A: "hello"};

box5.apply(obj,[88,99]);

//Max and min methods of apply

//If the first parameter is empty, the original object will not be changed

var arr2=[5,7,10,11,345,365];

console.log(Math.max.apply(null,arr2));//365

console.log(Math.min.apply(null,arr2));//5