【js重学系列】this

this概念

this用来指代当前代码执行上下文环境。

由于函数可以在不同的运行环境执行,所以需要有一种机制,能够在函数体内部获得当前的运行环境(context)。所以,this就出现了,它的设计目的就是在函数体内部,指代函数当前的运行环境。

this的指向规则

// 分为两种:
// 全局上下文指向 默认指向
// 函数上下文指向 this指向调用该函数的对象

1.默认指向

console.log(this); // window

    console.log(this);
}
foo()// window
// 全局上下文默认this指向window, 严格模式下指向undefined。

2.直接调用函数

let obj = {
    foo: function() {
        console.log(this);
    }
}
let foo2 = obj.foo;
foo2(); // window

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

3.对象.方法的形式调用

let obj = {
    foo: function() {
        console.log(this);
    }
}
obj.foo(); // obj

// this指向这个对象

4.DOM事件绑定

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

5.new+构造函数

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

6.箭头函数

箭头函数没有this,剪头函数的this是继承父执行上下文里面的this 
箭头函数没有this, 因此也不能绑定。里面的this会指向当前最近的非箭头函数的this,找不到就是window(严格模式是undefined)。比如:
let obj = {
  a: function() {
    let do = () => {
      console.log(this);
    }
    do();
  }
}
obj.a(); // 找到最近的非箭头函数a,a现在绑定着obj, 因此箭头函数中的this是obj

优先级

new > call、apply、bind > 对象.方法 > 直接调用。

其他this总结

http://www.ruanyifeng.com/blog/2018/06/javascript-this.html

https://segmentfault.com/a/1190000021764752

http://47.98.159.95/my_blog/blogs/javascript/js-api/006.html#_1-全局上下文

https://blog.csdn.net/weixin_44153194/article/details/103543060

https://www.cnblogs.com/pssp/p/5216085.html

https://blog.51cto.com/u_11871779/2129522

posted @ 2021-05-28 21:31  有风吹过的地方丨  阅读(70)  评论(0编辑  收藏  举报