javascript基础之五(this与闭包详解)
来源:互联网 发布:萃妮缇 知乎 编辑:程序博客网 时间:2024/06/05 00:22
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JavaScript的this与闭包详解</title></head><script>//JavaScript中函数内的this指的是执行函数的上下文 对象obj={fun:function(){ console.info("当前this是: " +this); }};obj.fun();//当前this是: [object Object] 因为此时执行函数的是objectvar v=obj.fun;v();//当前this是: [object Window] 应为此时执行函数的是window//也可以动态指定函数的上下文对象 call() apply()//call()window.name="window";person={name:"person"};function sayName(){ console.info("当前的this: "+ this +",当前的name: "+this.name); };sayName.call(person);//当前的this: [object Object],当前的name: person,因为通过call指定了函数执行上下文对象为person,则函数sayName中this指的就是personsayName.call(window);//当前的this: [object Window],当前的name: window//apply()var say=function(message){ console.info(this.name+" say "+message); }say.apply(person,["我是 person"]);//person say 我是 person 同call 指定上下文对象的同时,传入函数参数(使用数组传参数)say.apply(window,["我是 window"]);</script><body><h1 style="text-align:center">//回调函数的上下文this的指代//回调在函数</h1><h2 id="time1" style="text-align:center"></h2><h2 id="time2" style="text-align:center"></h2><script>//回调函数的上下文this的指代//回调在函数var outputEle1=document.getElementById("time1");var showTime=function(){ console.info("1当前this: " +this); if(!!outputEle1){ outputEle1.innerHTML=new Date().toLocaleString(); }}//setInterval(showTime,1000);//当前this: [object Window] 因为this与回调函数的上下文对象相同,这里回调函数为setInteval//被回调的函数在对象var obj={ outputEle2:document.getElementById("time2"), showTime:function(){ console.info("2当前this: " +this); if(!!this.outputEle2){ this.outputEle2.innerHTML=new Date().toLocaleString(); } }};setInterval(obj.showTime,1000);//当前this [object Window],不论是对象内的函数,函数中this上下文的指代回调函数setInterval(obj.showTime.bind(obj),1000);//当前this [object Window],当前通过bind方法指定了上下文对象为obj</script></body></html>
0 0
- javascript基础之五(this与闭包详解)
- JavaScript全面了解作用域(基础、this、闭包、继承)之二
- 【Web基础】JAVAScript基础之闭包详解
- Javascript学习之this与函数详解
- JavaScript闭包作用域与this
- javascript基础总结(五)--闭包
- JavaScript 之 this 详解
- javascript之this详解
- javascript之闭包基础
- JavaScript基础之闭包
- JavaScript 闭包 this
- javascript 之闭包详解
- JavaScript之闭包详解
- javascript之闭包详解
- JavaScript之作用域与闭包详解
- JavaScript之作用域与闭包详解
- JavaScript之作用域与闭包详解
- python基础系列(五)之闭包
- IOS网络笔记--使用视频播放
- 面向对象第三次作业部分参考代码
- JDK7目录监视服务
- 无法打开物理文件xxx.mdf操作系统错误 5:“5(拒绝访问。)” (Microsoft SQL Server,错误: 5120)的解决方法
- Android Material Design之Toolbar与Palette实践
- javascript基础之五(this与闭包详解)
- eclipse启动tomcat
- Hadoop2.6.1中的Reducer实现
- Matlab 并行编程——CUDA
- Android 常用colors xml
- 设计模式-工厂模式
- MAC OS EI Capitan系统文件修改
- hdu acm 3535 AreYouBusy
- Android基础和运行机制