回顾一下 JavaScript 中 this 的指向问题(非严格模式下的 this 指向)
函数的不同调用方式决定了 this 的指向不同
- 普通函数 this 指向 window
function fn() {
console.log('普通函数的this' + this);
}
window.fn();
- 对象的方法 this 指向的是对象
var o = {
sayHi: function() {
console.log('对象方法的this:' + this);
}
}
o.sayHi();
- 构造函数 this 指向 构造函数new出来的实例对象,原型对象里面的this也是指向它
function Star() {};
Star.prototype.sing = function() {}
var ldh = new Star();
- 绑定事件函数 this 指向的是函数的调用者
var btn = document.querySelector('button');
btn.onclick = function() {
console.log('绑定时间函数的this:' + this);
};
- 定时器函数 this 指向的是window
window.setTimeout(function() {
console.log('定时器的this:' + this);
}, 1000);
- 立即执行函数 this 指向的是window
(function() {
console.log('立即执行函数的this' + this);
})();
要牢记一点:当前函数的 this 是在函数被调用执行的时候才确定的。