this指向的不同场景:
一、普通函数调用
普通函数中的this是谁?===>window
function f1() {
console.log(this);//window
}
f1();
严格模式下的普通函数中的this?
"use strict";//严格模式
function f1() {
console.log(this);
}
f1();//undefined
window.f1(); //==>window
//严格模式下调用函数,它会认为函数就是方法
//方法通过对象调用,你的对象没写
二、定时器函数
window.setInterval(function () {
console.log(this); //window
},1000);
三、构造函数调用
function Person(){
console.log(this);//Person==>实例对象
}
var per=new Person();
console.log(per);
四、对象方法调用
function Person(){
console.log(this);//Person==>实例对象
this.sayHi=function () {
console.log(this);//Person==>当前实例对象
};
}
var per=new Person();
console.log(per);
per.sayHi();
五、原型对象调用
function Person(){
console.log(this);//Person==>实例对象
this.sayHi=function () {
console.log(this);//Person==>实例对象
};
}
Person.prototype.eat=function () {
console.log(this);//Person==>实例对象
};
var per=new Person();
console.log(per);
per.sayHi();
per.eat();
总结
本章总结了js中经常见到的this指向问题,汇总如下表:
调用方式 | 非严格模式 | 备注事项 |
---|---|---|
普通函数 | window | 严格模式下是undefined |
定时器函数 | window | |
构造函数 | 实例对象 | |
对象方法 | 该方法所属对象 | 临近的对象 |
原型对象方法 | 实例对象 | |
事件绑定方法 | 绑定事件对象 |
以上。