JavaScript中this关键字指代总结
来源:互联网 发布:苹果电脑 查看mac地址 编辑:程序博客网 时间:2024/05/01 23:23
JavaScript中this关键字指代总结
在JavaScript中,this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
总的原则:this指的是调用函数的那个对象。
1. 纯粹的函数调用
/*情况一:纯粹的函数调用*//*this代表全局对象*/var x = 1;var y = 2;function test1(){ this.y = 20; console.log(this.x); console.log(this); //Window}test1(); //1console.log(y); //20
2. 作为对象的方法调用
/*情况二:作为对象方法的调用*//*this代表上下文*/var o = {};o.x = 3;o.m = test2;o.m(); //3function test2(){ console.log(this.x);}
<!DOCTYPE html><html><head></head><body> <p id="txt"></p> <button id="btn">Testbtn</button> <script type="text/javascript"> /*addEventListener()的作用域为元素作用域*/ /*this代表DOM元素*/ document.getElementById("btn").addEventListener("click", function(){ document.getElementById("txt").innerHTML = "Hello World-addEventListener"; console.log(this.id); //btn }); </script></body></html>
3. 作为构造函数
/*情况三:作为构造函数*//*this代表通过构造函数生成的新对象*/function test3(){ this.x = 5;}var o2 = new test3();console.log(o2.x); //5
4. apply/call调用
/*情况四:apply/call调用*//*this代表改变后调用这个函数的对象*/var X = 100;function test4(a,b,c){ console.log(this.X + "-" +String(a) + "-" + String(b) + "-" + String(c)); }var o3 = {};o3.X = 7;var o4 = {};o4.X = 9;o3.m = test4;o3.m.apply();//参数为空时,默认调用全局对象:100-undefined-undefined-undefinedo3.m.apply(o3); //7-undefined-undefined-undefinedo3.m.call(); //100-undefined-undefined-undefinedo3.m.apply(o4,[1,2,3]); //9-1-2-3o3.m.call(o4,1,3,4,5); //9-1-3-4o3.m.apply(o4,[1,2]); //9-1-2-undefined
0 0
- JavaScript中this关键字指代总结
- JavaScript中this的指代问题
- javascript-this对象指代
- THIS的指代总结
- javascript中this关键字---总结2
- 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关键字详解
- cas单点登录----ticket的过期策略(ticketExpirationPolicies.xml)
- Docker:手动配置容器网络
- AOP验证参数是否合法
- 解决 Eclipse使用SVN插件提交代码报错 Base checksum mismatch
- python读取excel数据
- JavaScript中this关键字指代总结
- hbase源码分析-负载均衡过程
- 基于 Open vSwitch 的 OpenFlow 实践
- Surfaceview调用Camera实现拍照
- 基于Mininet,搭建简单的sFlow测试环境
- Swift3.0中十六进制颜色转换UIColor
- 【01背包求方案数】HDU4815-Little Tiger vs. Deep Monkey
- 【华为练习题 】 字符串的最小周期(中级)
- Java基础语法(二)---函数与数组