this 是在函数执行的时候决定的,而不是定义的时候决定的!!!
this 指向也是有原则的,一般this执向调用者本身
我们简单来看下不同函数的this 指向问题
// 普通函数this 指向window
function run() {
console.log(this);
}
window.run() // 完整的写法是这样的,window是调用者,普通函数this指向window
// 对象方法 this指向o
var o = {
say() {
console.log(this);
}
}
o.say() //对象方法this 指向的是o这个对象,因为是o调用的
// 构造函数 this指向实例对象ldh
function Start() {
start.prototype.eat = function(){}
}
var ldh = new Start() // 构造函数的this 指向实例对象ldh ,原型对象里面的this 也指向ldh这个实例对象
// 绑定事件函数 this指向实例对象btn
btn.onclik = function(){
console.log(this);
} // 绑定事件的函数的this 指向btn这个实例
// 定时器函数 this指向实例对象window
window.setTimeout(()=>{
console.log(this)},1000) // this指向window
立即执行函数 this指向window
(function(){console.log(1);})() // 立即执行函数 this指向window