this的指向在函数定义的时候确定不了,只有函数执行的时候才能确定this指向谁,一般this最终指向调用它的对象
this指向三种情况
-
全局作用域或者普通函数中this指向全局对象window(定时器里面的this指向window对象)
-
方法中调谁用this的指向谁
-
构造函数中this指向构造函数的实例
代码演示
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>333333</title>
<style>
</style>
</head>
<body>
<button>点击</button>
<script>
//this指向问题 一般情况下this最终指向的是调用它的对象
//全局作用域或者普通函数中this指向全局对象window(定时器里面的this指向window对象)
console.log(this);
function fn() {
console.log(this);
}
window.fn();
window.setTimeout(function () {
console.log(this);
}, 1000)
//方法中调谁用this的指向谁
var o = {
sayHi: function () {
console.log(this);
}
}
o.sayHi();
var btn = document.querySelector('button');
btn.onclick = function fn() {
console.log(this);//this指向的是btn指着对象
}
btn.addEventListener('click', function () {
console.log(this);
});
//构造函数中this指向构造函数的实例
function Fun() {
console.log(this);
}
var fun = new Fun();
</script>
</body>
</html>