This points to a lot of troublesome cases, remember the rules of the game, in order to “constant” should “change”.
Brain map dessert:
Common function
Call a function directly:
Global environment strict mode this = undefined, non-strict mode this = window
function fn1() {
'use strict'
console.log(this)
}
function fn2() {
console.log(this)
}
fn1(); // Window
fn2(); // undefined
Copy the code
Constructor:
This = constructor instance
function fn1() {
this.name = "fn1";
console.log(this);
}
var fn2 = new fn1();
console.log(fn2.name) // fn1
Copy the code
Method calls, that is, objects. Methods:
This = the object on which the function is called
var o1 = {
name: 'o1',
fn: function () {
return this.name;
}
}
var o2 = {
name: 'o2',
fn: o1.fn
}
console.log(o2.fn()) // o2
Copy the code
Apply, call, bind
The apply and call parameters are different, and bind needs to be executed
var obj = {}; fn.call(obj, 'arg1', 'arg2'); var obj = {}; fn.apply(obj, ['arg1', 'arg2']); var obj = {}; fn.bind(obj, 'arg1', 'arg2')();Copy the code
Arrow function
This = this of the function that wraps the arrow function (proximity rule), this is not found, and the result is the same as the global pattern
var obj = {
name: 'obj',
fn: function () {
this.name = 'fn'
let func = () => {
console.log(this.name)
}
func();
}
}
obj.fn(); // fn
Copy the code
Dom binding events
This in onclick and addEventerListener points to the element of the binding event by default, IE points to attachEvent, and other Windows
Tip: You can use arrow functions in events to avoid this being changed
priority
Arrow functions > New > Apply, Call,bind > objects. Methods > Direct Call (global environment)