function a(){
this.count=5;
this.a=document.getElementById('aaa');
this.a.addEventListener('click',function(event){
//如何能拿到count的值???拿到事件外部的引用
},false)
}
this.count=5;
this.a=document.getElementById('aaa');
this.a.addEventListener('click',function(event){
//如何能拿到count的值???拿到事件外部的引用
},false)
}
function a(){
var self=this ;
this.count=5;
this.a=document.getElementById('aaa');
this.a.addEventListener('click',function(event){
alert(self.count)//通过定义的变量self去引用,事件中的this引用指向的是触发事件的HTMLELEMENT元素
},false)
}
var count=5;
this.a=document.getElementById('aaa');
this.a.addEventListener('click',function(event){
alert(count);
},false)
}
<!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>无标题文档</title>
</head><body>
<div id="aaa" style="width:100px;height:100px;background:#000000;"></div>
<script type="text/javascript">
function a(){
this.count=5;
this.a=document.getElementById('aaa');
this.a.addEventListener('click',function(event){
//如何能拿到count的值???拿到事件外部的引用
alert(count);
},false)
}
a();
</script>
</body>
</html>
#2的方法也是可以的。但是把他本来的属性变量改成了局部变量
#3的方法只有在a()函数是顶层function的时候才是对的。所以最正确的做法是
function a(){
this.count=5;
this.a=document.getElementById('aaa');
var targetThis = this;
this.a.addEventListener('click',function(event){
//如何能拿到count的值???拿到事件外部的引用
alert(targetThis.count);
},false)
}
#3中如果只是count的传入,函数应该会一级一级往上查找该变量,直到global。
还望解释下。
this.count=5;
this.a=document.getElementById('aaa');
var temp= this;
this.a.addEventListener('click',function(event){
//如何能拿到count的值???拿到事件外部的引用
alert(temp.count);
},false)
}
还有就是#3中count的传入,编译器会逐级网上找吗?我觉得会报没定义的错误,还是去试下。
直接调用
a();
那么里面的this,直接指向window
而,你里面的count,由于并没有挂靠对象。也就直接指向window。所以能够取到但是如果new a();
那就不对了
new a()后,type变成object,this换成指向这个obj。
和new a();
this的指向完全不同
对象冒充说白了,和call和apply原理基本一样。
我想说的是,a()中的this根本不可能指向window。