您的位置:首页 > Web前端 > JavaScript

【JS】【this关键字】

2017-12-25 11:27 232 查看

- 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对象
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript