JavaScript 的 this
来源:互联网 发布:网络光纤传输器 编辑:程序博客网 时间:2024/06/06 07:15
学习了js这么久了,一直没有弄懂js中的this到底是什么鬼,有时候它是全局变量,有时候它指向全局变量,(在浏览器中是 window变量),有时候又指向对象。下面为大家做一个总括。
参考:http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/#ibm-pcon
第一种情况:对象中的函数this指向这个对象
//声明对象var obj = { data:"data", test:function(){ console.log(this.data); }}obj.test();//输出data
第二种情况:普通函数中的this指向全局变量(window)
function Point(x,y){ this.x = x; this.y = y; this.showXY = function(){ console.log(this.x+" "+this.y); }}Point(4,5);//执行Point函数后,为window.x window.y 赋值showXY();//执行全局的window.showXY()函数,读取全局x,y
第三种情况:将函数当作构造函数调用的话this指向新的对象
function Point(x,y){ this.x = x; this.y = y; this.showXY = function(){ console.log(this.x+" "+this.y); }}var ins = new Point(5,6);ins.showXY();
第四种情况:调用apply和call函数,this指向对象参数
function Point(x,y){ this.x = x; this.y = y; this.showXY = function(){ console.log(this.x+" "+this.y); }}var obj2 = { x:0,y:0};Point.apply(obj2,[78,5]);showXY.apply(obj2);//这儿的this指向的是obj2这个对象
0 0
- javascript的this使用
- 关于JavaScript的this
- Javascript的this用法
- Javascript的this用法
- Javascript的this用法
- Javascript的this用法
- Javascript的This用法
- Javascript的this用法
- javascript的this关键字
- Javascript的This用法
- Javascript的This用法
- JavaScript的"this"
- 简析javascript的this
- Javascript的this用法
- Javascript的this用法
- Javascript的this用法
- Javascript的this用法
- JavaScript的this关键字
- 4.7.1:EL表达式
- 存储过程基本语法的小Demo
- lucene的一段测试代码
- Linux下高性能网络编程中的几个TCP/IP选项_SO_REUSEADDR、SO_RECVBUF、SO_SNDBUF、SO_KEEPALIVE、SO_LINGER、TCP_CORK、TCP_NODE
- 运行成功的最新进度条代码
- JavaScript 的 this
- 最高分是多少
- Redis 集成Spring(spring-data-redis)
- BZOJ 3933 CQOI2015 多项式 高精度
- Maya/3Ds MAX与OpenGL的联系
- jvm 关于初始化时<cinit> , <init>的调用。
- 浏览器兼容模式页面错乱 兼容模式和急速模式
- GIT 工具如何入门使用---我手把手教你windows环境下的git使用
- fragment使用