Whoever calls this points to whoever
By default:
In normal functions this refers to window;
Method this refers to the caller;
The function this in the event refers to the event source;
In the constructor, this refers to the current instance object;
This in the timer points to the window;
This in the self-executing function points to window;
The this in the arrow function points to the caller in the parent scope; (Do not use this arbitrarily in arrow functions, use it after watching carefully)
Arrow functions cannot be used as constructors
Strict mode
Enable strict mode “use strict”; (at the beginning of the scope);
This in ordinary functions
In normal mode, this refers to window; in strict mode, this refers to undefined.
Change the direction of this
1. The call method
Call (this refers to a,b,c,d…) The following parameters are used for passing arguments
The function calls the call method, which in turn calls the function execution, changing the this reference during execution
Write null when you don’t need to change this;
function fn(a, b, c) { console.log(this, a, b, c); } let obj = {uname: 'obj ', age: 22,} fn. Call (obj, 2, 4, 6); */ function Father(uname, age) { this.uname = uname; this.age = age; } function Son(uname, age) { // this.uname = uname; // this.age = age; Father.call(this, uname, age); } let obj = new Son(' wangdefa ', 22); console.log(obj);Copy the code
2. The apply method (may be used when manipulating arrays)
Apply (a,b,c,d… ) is passed in the way of array, there are several values in the array to write several values, transfer will be one to one corresponding transfer
let arr = [23, 66, 16, 7, 9, 5]; // let res = Math.max.apply(null, arr); let res = Math.max(... arr); console.log(res);Copy the code
Write null when you don’t need to change this; Residual operators… You can expand an array; . If used to receive the value, it means to receive the remaining value;
3. The bind method
Bind does not execute a function, but rather returns a function that changed this
Bind (this to a,b,c,d…) ;
function fn(a, b, c) { console.log(this, a, b, c); } let obj = {uname: 'obj ', age: 22,} let res = fn. Bind (obj, 2, 4, 6); res(); // Need to call againCopy the code