/**
* this的指向
* 函数的不同调用方式决定了this的指向不同
*/
// 1.普通函数中this指向window
function fn() {
console.log('普通函数')
}
fn(); // this指向window 也就是函数的调用者 完整的写法是 window.fn()
// 2.对象的方法 this指向的是对象
var obj = {
sayHi: function() {
console.log('对象的方法')
}
}
obj.sayHi(); // this指向obj对象
// 3.构造函数 this指向创建的实例对象
function Star() {};
Star.prototype.sing = function() {
console.log(this,'pppp')
}
// 原型对象里面的this指向也是ldh这个实例对象
var ldh = new Star(); // this指向ldh
console.log(ldh.sing());
// 4.绑定事件函数 this指向是函数的调用者 bnt这个按钮对象
var btn = document.querySelector('button');
btn.onclick = function() {
console.log(this,'绑定事件函数的this')
}
// 5.定时器函数 this指向是window 函数的调用者
// 定时器的完整写法是
// window.setTimeout(function() {
// console.log(this,'定时器this')
// })
// 6.立即执行函数 this指向window
// (function() {
// console.log('立即执行函数')
// })();
<button>按钮</button>