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
原创粉丝点击