this关键字
函数中的this,this的指向与定义和执行位置没有关系,只关注函数执行前面是否有“.”,有的话则指向“.”前面的对象,如果有多个“.”,指向最近的那个点前面的对象(上一级对象),没有的话指向window,严格模式是undefined
- 自执行函数执行,this用于指向window(严格模式下undefined)
- 普通函数执行,函数前面有’.’指向’.’前面的对象,如没有则指向window(严格模式下undefined)
- 给元素的一个行为事件绑定方法,行为执行时,该方法的this指向该元素
- 构造函数中this,在创建实例时候指向实例本身
- call/apply/bind,this指向参数对象(优先级最高,上面4中与第5种同时存在时,以第5个为准)
实战
// 一
var b={
x:12,
func:function(){}
}
window.b.func() // this指向上一级对象b
var c=b.func;
window.c() // this指向上一级对象window
// 二
var obj=document.getElementById('div1');
obj.onclick=function(){
console.log(this); //this->该元素
}
function fn(){
console.log(this);
}
obj.onclick=fn;//this ->元素
obj.onclick=function(){
//this->元素
fn() //this ->window
}
// 三
!function(){
console.log(this)
}()
// 四
function fn(){
console.log(this);
}
var obj={fn:fn};
fn(); //this->window
obj.fn()//this->obj
function sum(){
fn();// this -> window
}
sum()
var oo={
sum:function(){
console.log(this) //this->oo
fn() // this->window;
}
}
oo.sum();