什么是this?
环境对象
指的是函数内部特殊的变量 this
,它代表着当前函数运行时所处的环境
this的指向
全局环境
在一个js文件或<script>
标签内,this始终指向window对象
console.log(this) // 全局环境,即window对象下,this -> window
局部环境
严格模式下,函数中的this为undefined
1.在全局作用域下直接调用函数,this指向window
function fun() {
console.log(this)
}
fun() // fun() 实际上是window.fun(), 所以this -> window
2.对象函数调用,哪个对象调用就指向哪个对象
let obj = {
name: 'liao',
sayHi: function () {
console.log('hi~', this.name)
},
}
let name = 'Li'
obj.sayHi() //hi~ liao this ---> obj
3.new实例对象,构造函数中的this指向实例对象
function Person(){
this.name = "liao" // 这里的this -> obj对象
}
let obj = new Person()
4.事件中的this
在HTML事件句柄中,this指向了接收事件的HTML元素
<button onclick="console.log(this)">点我</button>
this --> button
改变this指向
call / apply / bind
总结
1.在函数调用中,this指向调用它的对象。
2.在构造函数中,this指向实例化对象。
3.在事件体中,this指向事件源。
4.箭头函数中,没有this
5.其他情况中,this指向window
发表回复