javascript基础之五(this与闭包详解)
2015-10-23 20:25
831 查看
<!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] 因为此时执行函数的是object var 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指的就是person sayName.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>
相关文章推荐
- seajs3.0.0源码分析记录
- JS播放声音 兼容所有浏览器
- javascript基础之四(数组详解)
- javascript基础之三(对象详解)
- jsp文件开头<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 > 有什么用
- javascript基础之二(变量作用域的各种啃)
- javascript基础之一(函数)
- javascript基础一(变量与函数)
- 轻松学习JavaScript二:JavaScript语言的基本语法要求
- JS Replace全部替换字符方法
- js动态生成选项之考试系统(一)
- 如何向以json对象为元素的数组中追加一个新的元素
- JavaScript 类式继承与原型继承
- JSON和XML优缺点的比较
- js 程序执行与顺序实现详解
- js常用函数
- Tabris.js 介绍与学习<3>
- js 解析key值为数字的json的问题
- 102 seajs popup 兼容性问题
- JS判断移动设备最佳方法