相信很多人学到this 时就会多多少少感觉到了迷惑,下面就逐个分析一下
this
this在不同函数调用的情况下有着不同的指向,下面列举6种不同的函数一一说明
一.普通函数
普通函数的调用下this指向window,可以通过下面的代码加以验证
<script>
function say() {
console.log(this);
}
say();
</script>
不难得出这样的结论,因为我们在调用say()的时候省略了window.say()的window
二.构造函数
构造函数调用下this指向该构造函数的实例对象
<script>
function Student(uname, age, sex) {
this.uname = uname;
this.age = age;
this.sex = sex
console.log(this);
}
var ming = new Student("ming", 18, "男");
</script>
三.对象方法
对象方法的this指向该方法所属的对象
<script>
var student = {
say: function() {
console.log(this);
}
}
student.say();
</script>
四:事件绑定方法
事件绑定方法的this指向绑定事件的对象
<script>
var button = document.querySelector('button');
button.onclick = function() {
console.log(this);
}
</script>
五.定时器函数
定时器函数中的this指向window
<script>
setTimeout(function() {
console.log(this);
}, 2000)
</script>
六.立即执行函数
立即执行函数中的this指向window
<script>
(function() {
console.log(this);
})()
</script>