this 关键字
1.1 在对象方法中,this 表示该方法所属的对象
1.2 如果单独使用,this 表示全局对象
在浏览器中,this
表示 Window 对象
在 Node 环境,this
表示 Global 对象
1.3 在函数中,this 表示全局对象
1.4 严格模式下,在函数中,this 是未定义的(undefined)
1.5 在事件中,this 表示接收事件的元素
1.6 call() 和 apply() 方法可以将 this 引用到任何对象
call()
和apply()
将对象person1
的getUserName
方法中的this
引用到person2
中,也就是说,此时getUserName
中的this
指向的是person2
,而不是person1
。
1.7 构造函数中的 this
在
new Person()
时,会创建一个新的对象,此时构造函数 Person 中的this
就指向了新的对象
1.8 总结(Your Donot Know JS)
this
是 JS 中的动态作用域机制,具体来说有四种,优先级由低到高分别如下:
- 默认的
this
绑定,就是说,在一个函数中使用了this
,但是没有为this
绑定对象,这种情况下,非严格模式下,this
就是全局变量(如 1.2 和 1.3),严格模式下,this
是undefined
(如 1.4)。 - 隐式绑定:使用
userInfo.getUserName()
这样的语法来调用函数的时候,函数getUserName
中的this
绑定到userInfo
对象(如 1.1)。 - 显示绑定:
person1.getUserName.call(person2, ...)
,person1.getUserName.apply(person2, [...])
这样的语法时,getUserName
中的this
绑定到person2
对象(如 1.6)。 - 构造绑定:
new person()
,这种情况,无论person
是否做了绑定,都要创建一个新的对象,然后person
中的this
指向了这个新的对象(如 1.7)。
参考资料:
https://juejin.cn/post/6844903511868571656
http://www.ruanyifeng.com/blog/2018/06/javascript-this.html
https://note.youdao.com/ynoteshare1/index.html?id=b2fab3b044aa90033395df0c8c9ca3a4&type=note