环境对象
能够分析判断函数运行在不同环境中 this 所指代的对象。
环境对象指的是函数内部特殊的变量 this ,它代表着当前函数运行时所处的环境。
每个函数里都有this环境对象,普通函数里this指向的是window
- this 本质上是一个变量,数据类型为对象
- 函数的调用方式不同 this 变量的值也不同
- 【谁调用 this 就是谁】是判断 this 值的粗略规则
- 函数直接调用时实际上 window.sayHi() 所以 this 的值为 window
<button>click</button>
<script>
const btn = document.querySelector('button')
btn.addEventListener('click', function () {
this.style.color = 'red'
})
</script>
回调函数
如果将函数A作为参数传递给函数B时,我们称函数A为回调函数。
- 回调函数本质还是函数,只不过把它当成参数使用
- 使用匿名函数做为回调函数比较常见
举例:
<script>
function fn() {
console.log('我是回调函数...');
}
// 调用定时器
setInterval(fn, 1000);
</script>
fn 函数做为参数传给了setInterval
,这便是回调函数的实际应用了,结合刚刚学习的函数表达式上述代码还有另一种更常见写法。
<script>
// 调用定时器,匿名函数做为参数
setInterval(function () {
console.log('我是回调函数...');
}, 1000);
</script>