- this是调用该函数的对象;
1.代表普通对象
function User(){
this.dowork=function(){console.debug(this)};
}
var user =new User();
user.dowork();//由user调用dowork函数,所以this代表user.
2.代表window对象
var dowork1=function(){console.debug(this);}
function dowork2(){console.debug(this);}
dowork1();dowork2();//以上这两中声明方式,不论在哪里,由window调用
(function(){console.debug(this);})(); //匿名函数,由window调用
3.代表HTMLDocument对象
//这个是jQuery的页面载完调用的函数
$(function(){
console.debug(this); //返回HTMLDocument对象
})
- 修改函数的调用者
函数存在于堆中,任何对象都可以去调用该函数,从而使得函数中的this不是固定死的.
方式1
function User(){
this.dowork=function(){console.debug(this)};
}
var user =new User();
window.dowork=user.dowork;
window.dowork(); //输出window对象
方式2. 函数.call(对象,形参1,形参2)
function User(){
this.dowork=function(){console.debug(this)};
}
var user =new User();
user.dowork.call(window); //输出window对象
方式3. 函数.apply(对象,[形参1,形参2])
function User(){
this.dowork=function(){console.debug(this)};
}
var user =new User();
user.dowork.apply(window);//输出window对象