判断 this 指向的唯一依据就是由谁调用
回调函数
- 实验发现,定时器中的回调函数总是指向 window 对象。
- 找不到调用者统统指向 window 对象
- 函数 bind 方法可以固定 this 指向,结果会返回一个新的函数
全局函数调用 this 指向全局对象 window
ts
function show(){
console.log(this) // 输出window对象
}
show() // 调用可省略window.实例化对象的 this 指向调用对象
- 类模板中的 this 为默认占位符,未实例化则无意义
- 实例化后的对象的 this 指向 new 出来的对象
- 类中函数和属性要相互调用都需要通过 this 相互调用
事件函数绑定的函数中的 this 指向源对象
ts
// 获取按钮元素
var button = document.getElementById('myButton');
// 为按钮绑定点击事件处理函数
button.onclick = function() {
// 在事件处理函数内部,this 指向触发事件的按钮元素
console.log(this); // 输出按钮元素,可以在控制台中查看
};箭头函数内的 this 指向父对象
箭头函数捕获上下文的 this 作为自己的 this。
ts
const user = {
id: 1,
name: "xiaowang", // this的父级作用域,再上一级就是全局(window对象)
play:() => {
console.log(this)
}
}
user.play()