您的位置:首页 > Web前端 > JavaScript

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: