【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对象
相关文章推荐
- JS中this关键字的使用
- JS中的this关键字
- JS中this关键字详解
- js中的this关键字详解
- 变量对象,作用域链,闭包,匿名函数,this关键字,原型链,构造器,js预编译,对象模型,执行模型,prototype继承
- js中的this关键字
- JS作用域闭包、预解释和this关键字综合实例解析
- [js]02js预解释-作用域-this关键字
- js中this关键字的指向
- JS学习之闭包、this关键字、预解释、作用域综合
- Js中的this关键字(吉木自学)
- JS中内嵌函数中this关键字的使用
- 【js与jquery】javascript中的this关键字的理解
- 学习js即时执行函数中的this关键字详解
- JS学习—this关键字
- Js全局变量与局部变量_this关键字
- Node.js中的this关键字
- JS:this关键字的指向
- js中this关键字的用法
- 转:js中this关键字详解