前言

ES6中添加了箭头函数,可以更方便绑定this作用域了 O.o
至于使用,我觉得一个实例就够了 我不信看完还有不会用的

实例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const x = 1;
this.x = 4; // this default {}
global.x = 2;

let fun1 = () => {
console.log('fun1', this.x); // 4 this => this
};


const obj = {
x: 3,
fun: function () {
console.log('fun', this.x); // 3 this => obj
let fun2 = () => {
console.log('fun2', this.x); // 3 this => fun => obj
};
let fun3 = function () {
console.log('fun3', this.x); // 2 this => global
};
let fun4 = fun1;
let fun6 = fun3.bind(this);
fun1();
fun2();
fun3();
fun4(); // 4 this => this
fun6(); // 3 this => obj
}
};
obj.fun();
console.log(this); // { x: 4 }
console.log(this.x); // 4 this => this