Arrow functions have been added to ES6 for their simplicity and ease of getting this. Here’s a summary of the differences:
This under normal functions:
- In normal functions this always stands for its direct caller, and by default this refers to window,
- In strict mode, there is no direct caller’s function in which this is undefined
- Call,apply,bind(new in ES5) Bind,this refers to the bound object
This in the arrow function:
- The arrow function does not have its own this; its this is inherited; The default points to the object where it was defined (the host object),
- It’s not an object at execution time, and when you define it, maybe the environment is Window, maybe something else.
Common function
function test() {
console.log(this);
}
test(); //window
Copy the code
Test is a global function, which means that test() mounted under the window object is equivalent to window.test();
var obj = {
func: function () {
console.log(this);
setTimeout(function () {
console.log(this);
},0);
}
}
obj.func();
// obj, where this is an obj object
// window
Copy the code
Func is hosted by obj, so this in func is obj. The timer function has no default host object, so this refers to this in window strict mode:
function test() {
'use strict';
console.log(this);
}
test();
//undefined
Copy the code
Strict mode
In strict mode, this is undefined in a function that has no direct caller
"use strict";
var obj={
say:function(){
console.log(this); }}; obj.say();//obj
Copy the code
This, which has a direct caller, is its caller
Arrow function
var obj = {
say: function () {
setTimeout((a)= > {
console.log(this);
});
}
}
obj.say();
// obj
Copy the code
This inherits from obj and refers to the object that defines it, obj, not window
var obj = {
say: function () {
var f1 = (a)= > {
console.log(this); // obj
setTimeout((a)= > {
console.log(this); // obj
})
}
f1();
}
}
obj.say()
Copy the code
Since this in the function where f1 is defined refers to obj, the arrow function this in setTimeout inherits from F1, so it is obj regardless of multiple levels of nesting
var obj = {
say: function () {
var f1 = function () {
console.log(this);
setTimeout((a)= > {
console.log(this); })}; f1(); } } obj.say()// window, when f1 is called, there is no host object, the default is window
// window
Copy the code
The arrow function has no this binding and must determine its value by looking up the action chain. If the arrow function is contained by a non-arrow function, then this binds the this of the nearest non-arrow function; Otherwise. The value of this is set to undefined. The arrow function is defined in an environment equivalent to window, so the this function inside the arrow function is window