环境对象是什么?
环境对象指的是函数内部特殊的变量this,它代表着当前函数运行时所处的环境
环境对象的作用:
弄清楚 this 的指向,可以让我们的代码更简洁
函数调用的方式不同, this 指代的对象也不同,所以就有了判断 this 指向的粗略规则:“谁调用, this 就是谁“
(大家可以通过下面这段代码先体验一下环境对象)
<body>
<button>点击</button>
<script>
//每个函数里面都有this 环境对象 普通函数里面 this 指向的时window
function fn() {
console.log(this)
}
//普通函数里面 this 指向的时window 所以这里调用的函数 fn() 就相当于 Window.fn()
fn()
</script>
</body>
然后我们再来通过button来看一下在实际操作中 this 起到的作用
<body>
<button>点击</button>
<script>
const btn = document .querySelector(`button`)
btn.addEventListener('click' , function() {
console.log(this) //btn 对象
// 平常写法
//btn.style.color = 'red'
//使用 this 的写法
this.style.color = 'red'
})
</script>
</body>