js面向对象编程:this到底代表什么?
来源:互联网 发布:wampserver多域名绑定 编辑:程序博客网 时间:2024/05/16 07:42
在js中this的用法很让人迷惑,有些像Java或者C#中的this,但又不完全一样。按照流行的说法this总是指向调用方法的对象。
1、纯粹函数调用。
function ListCommon2(x) { this.x=x;alert("this 是 ListCommon2"+(this instanceof ListCommon2));alert("this.constructor"+this.constructor); } function test(){ //测试代码var t1=ListCommon2("烧水"); var t2=new ListCommon2("烧水2"); }经过测试发现,
如果不使用new,也就是var t1=ListCommon2("烧水");这样调用,this是全局对象Window对象,
如果使用new,也就是var t2=new ListCommon2("烧水2");;这样调用,this就变成了new出来的实例对象的应用,也就是 t2,
看来和调用方式也是有关系的。
2、作为方法调用,那么this就是指实例化的对象。
function ListCommon2(x) { this.x=x; this.Do=function(x)//特权方法 实例方法{ alert("this 是 ListCommon2"+(this instanceof ListCommon2)); alert("this.constructor"+this.constructor);} } ListCommon2.prototype.Do2=function()//实例方法 { alert("this 是 ListCommon2"+(this instanceof ListCommon2)); alert("this.constructor"+this.constructor); } function test(){ //测试代码var t1=ListCommon2("烧水");//t1.Do();调用错误//t1.Do2();调用错误 var t2=new ListCommon2("烧水2"); t2.Do(); t2.Do2(); }
经过测试发现,不管是特权方法类型的实例方法,还是原型类型的实例方法,this都指向了当前新创建的对象。
3 apply,call调用
apply的第一个参数就是this,如果没有传递this就是全局对象。
改变this的方法,通过new可以改变,使用call和apply也可以改变
4 setTimeout中的this
function ListCommon2(x) { this.x=x; this.Do=function(x)//特权方法 实例方法{ window.setTimeout(function(){ alert("this 是 ListCommon2"+(this instanceof ListCommon2)); alert("this.constructor"+this.constructor); },100); } } ListCommon2.prototype.Do2=function()//实例方法 { window.setTimeout(function(){ alert("this 是 ListCommon2"+(this instanceof ListCommon2)); alert("this.constructor"+this.constructor); },100); } function test(){ //测试代码 var t2=new ListCommon2("烧水2"); t2.Do(); t2.Do2(); }
测试发现setTimeout中的this也是全局对象Window对象,当然这样的例子还有很多,感觉应该是实例化的对象,可实际上却不是。因此需要注意。
参考文章
js中this的用法
js中this的总结
1 0
- js面向对象编程:this到底代表什么?
- js面向对象编程:this到底代表什么?第二篇
- js中的this到底指什么?
- js_day15--js面向对象编程+this关键字+成员函数
- 面向过程、基于对象、面向对象,到底有什么区别?
- 面向过程、基于对象、面向对象,到底有什么区别?
- js 面向对象编程
- js 面向对象编程
- js 面向对象编程
- JS面向对象编程
- js面向对象编程
- Js面向对象编程
- JS面向对象编程
- js面向对象编程
- js面向对象编程
- js面向对象编程
- js面向对象编程
- js面向对象编程
- 删除录音机还未保存的文件,后点击保存,录音机自动退出
- ExtJS学习05事件处理机制
- Android判断4G网络
- nodejs
- 滑动Pop Navigation
- js面向对象编程:this到底代表什么?
- 欢迎大家来到我的blog
- oracle数据库性能优化方案精髓整理收集回顾
- kvc 未完成
- JavaScript(22)jQuery 遍历
- 2013提高组 火柴排队
- session登陆判断
- MySQL的Catalog表
- spring整合struts1三种方式