<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">测试</button>
</body>
<script>
/*
this的指向问题:
//普通函数中的this,指向window
function fn() {
consolr.log(this)
}
window.fn();
//2.立即执行函数中的this,this指向的是window
(function () {
console.log(this)
})();//window
//3-定时器中的this,window
var timer = window.setInterval(function () {
console.log(this)
}, 5000)
//4-事件处理函数中的this,this代表绑定事件的对象
var btn = document.getElementById("btn");
btn.onclick = function () {
console.log(this);
}
//5-对象方法中的this,this指向的是当前的对象
var obj = {
x: 1000,
fn: function () {
console.log(this)
}
};
obj.fn()*/
//6-构造函数中的this,原型中的this都指向的是实例化对象
function Person(name) {
this.name = name
this.fn1 = function () {
console.log(this)
};
}
Person.prototype.fn2 = function () {
console.log(this);
}
var p1 = new Person("lingling");//p1称之为实例化对象
console.log(p1);
// p1.fn1();
// p1.fn2();
</script>
</html>