js中的this指向问题
一、在全局环境下
全局环境下this指向window
console.log(this);
//Window对象
二、this在对象方法中
在对象方法中的this指向调用这个方法的对象
let obj={
name:'王也',
fn1:function Fun(){
console.log(this);
}
}
obj.fn1()
//结果为 {fn1: ƒ Fun() name: "王也"}
三、事件绑定中的this
事件绑定中的this指向触发事件的DOM元素
<button>点我</button>
<script>
var btn=document.querySelector('button')
btn.onclick=function(){
console.log(this);
}
</script>
//结果为 <button>点我</button>
四、全局函数中的this
在严格模式下指向undefined,普通模式下指向window
function fn(){
console.log(this);
}
fn()
//返回结果为为window全局对象
五、内部函数中的this
内部函数中的this指向全局对象
function fn(){
setTimeout(function(){
console.log(this);
},0)
}
fn()
//返回结果为为window全局对象
六、构造函数中的this
构造函数中的this指向使用new创建的新对象本身
function showName() { this.name = "showName function"; }
var obj = new showName();
console.log(obj.name); //showName function
七、箭头函数中的this
箭头函数中的this指向有以下三种说法
- 普通函数谁调用指向谁,箭头函数在哪里定义指向谁
- 箭头函数外this指向谁就指向谁
- 箭头函数没有this指向
let obj={
name:'彭于晏',
fn1:function fn(){
setTimeout(()=>{
console.log(this);
},0)
}
}
obj.fn1()
//返回结果为 {fn1: ƒ fn(),name: "彭于晏"}