显示绑定场景:
call/apply/bind可以
/*直接执行了函数apply方法和call方法相似apply也可以有多个参数,但是不同的是,第二个参数必须是一个数组*/fn.call(thisObj, 参数1, 参数2, ...)fn.apply(thisObj, [参数1, 参数2, ...])function show() {console.log('我的名字是:', this.name);}const b = {name: 'Blue'};const c = {name: 'Change'}; //const d = {name: 'Dot'}show.call(b);// 我的名字是: Blueshow.apply(c);// 我的名字是:Change// bind 生成了一个新的函数 - this被绑定了的// let newFn = fn.bind(thisObj);show.bind(d)(); // 我的名字是: Dotlet show2 = show.bind(d);show2(); // 我的名字是: Dot
隐式绑定的场景:
- 全局上下文
- 直接调用函数
- 对象.方法的形式调用
- DOM事件绑定(特殊)
- new构造函数绑定
- 箭头函数
1 全局上下文
全局上下文默认this指向window, 严格模式下指向undefined。
非严格模式下的this 找不到明确的this,算 window
严格模式下(”use strict”)- 找不到,算undefined
2 直接调用函数
let obj = {a: function() {console.log(this);}}let func = obj.a;func();
这种情况是直接调用。this相当于全局上下文的情况。
3 对象.方法的形式调用
还是刚刚的例子,我如果这样写:
obj.a();
这就是对象.方法的情况,this指向这个对象
4 DOM事件绑定
onclick和addEventerListener中 this 默认指向绑定事件的元素。
IE比较奇异,使用attachEvent,里面的this默认指向window。
5. new+构造函数
此时构造函数中的this指向实例对象。
6. 箭头函数?
箭头函数没有this, 因此也不能绑定。里面的this会指向当前最近的非箭头函数的this,找不到就是window(严格模式是undefined)。比如:
let obj = {a: function() {const b = () => {console.log(this)};b();}}obj.a(); // 找到最近的非箭头函数a,a现在绑定着obj, 因此箭头函数中的this是obj
