显示绑定场景:

call/apply/bind可以

  1. /*
  2. 直接执行了函数
  3. apply方法和call方法相似
  4. apply也可以有多个参数,但是不同的是,第二个参数必须是一个数组
  5. */
  6. fn.call(thisObj, 参数1, 参数2, ...)
  7. fn.apply(thisObj, [参数1, 参数2, ...])
  8. function show() {
  9. console.log('我的名字是:', this.name);
  10. }
  11. const b = {name: 'Blue'};
  12. const c = {name: 'Change'}; //
  13. const d = {name: 'Dot'}
  14. show.call(b);
  15. // 我的名字是: Blue
  16. show.apply(c);
  17. // 我的名字是:Change
  18. // bind 生成了一个新的函数 - this被绑定了的
  19. // let newFn = fn.bind(thisObj);
  20. show.bind(d)(); // 我的名字是: Dot
  21. let show2 = show.bind(d);
  22. show2(); // 我的名字是: Dot

隐式绑定的场景:

  1. 全局上下文
  2. 直接调用函数
  3. 对象.方法的形式调用
  4. DOM事件绑定(特殊)
  5. new构造函数绑定
  6. 箭头函数

1 全局上下文
全局上下文默认this指向window, 严格模式下指向undefined。
非严格模式下的this 找不到明确的this,算 window
严格模式下(”use strict”)- 找不到,算undefined

2 直接调用函数

  1. let obj = {
  2. a: function() {
  3. console.log(this);
  4. }
  5. }
  6. let func = obj.a;
  7. func();

这种情况是直接调用。this相当于全局上下文的情况。

3 对象.方法的形式调用
还是刚刚的例子,我如果这样写:

  1. obj.a();

这就是对象.方法的情况,this指向这个对象

4 DOM事件绑定
onclick和addEventerListener中 this 默认指向绑定事件的元素。
IE比较奇异,使用attachEvent,里面的this默认指向window。

5. new+构造函数
此时构造函数中的this指向实例对象。

6. 箭头函数?
箭头函数没有this, 因此也不能绑定。里面的this会指向当前最近的非箭头函数的this,找不到就是window(严格模式是undefined)。比如:

  1. let obj = {
  2. a: function() {
  3. const b = () => {console.log(this)};
  4. b();
  5. }
  6. }
  7. obj.a(); // 找到最近的非箭头函数a,a现在绑定着obj, 因此箭头函数中的this是obj