一、this关键字的使用方法
- 方法中的 this,指向调用方法的对象
- 全局环境下的 this ,指向全局对象
- 全局函数中的 this,指向全局对象
- 内部函数中的 this,指向全局对象
- 事件中的 this.指向触发事件的DOM对象
- 构造函数中的 this ,指向 new 创建的对象【面试题new 的作用】
- 箭头函数中的 this, 指向定义函数上下文的 this
- 使用 闭包, var 获取dom 的索引
<script>
/*
1、直接输出 this 指向全局对象
*/
// this
console.log(this) // window
// 全局函数其实是window (全局对象) 的方法
function fun(){
console.log(this)
}
window.fun();
// this 放在方法中,this指向调用这个方法的对象
let cat = {
name: "喵喵",
sayName(){
console.log("我是" + this.name)
}
}
cat.sayName();
</script>
<body>
<button>按钮</button>
<script>
const btn = document.querySelector("button");
btn.onclick = function(){
console.log(this);
}
</script>
</body>
<script>
// new 关键字做了什么:new 会创建对象,将构造函数中的 this 指向创建出来的对象
// 构造函数:是用来创建对象
function F(){
this.name = "小明";
}
let f = new F();
console.log(f);
// 箭头函数没有 this
/*
1、普通函数,谁调用谁指向谁,箭头函数:在哪里定义指向谁
2、箭头函数外指向谁就指向谁
3、箭头函数中没有 this
*/
let cat = {
name: "喵喵",
sayName(){
setTimeout(()=>{
console.log(this)
},1000)
}
}
cat.sayName();
</script>