【JS】【this关键字】

- 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对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值