在一个对象里,添加鼠标点击事件,而和事件关联的函数中的this就变成了点击的dom对象.而我想要的是原对象.<!doctype html>
<html>
<body>
<div id=a style="width:10px;height:10px;background-color:red"></div>
<script type="text/javascript">
var aa = {
a : 4,
b : function() {
alert(this.a);
},
c : function() {
this.bb=8;
document.getElementById("a").onclick=this.d;
},
d:function() {
alert(this);
alert(this.a);
alert(aa.a);
}
}
aa.c();
</script>
</body>
</html>能否在点击时d函数中的this是aa而不是点击的那个dom.
<html>
<body>
<div id=a style="width:10px;height:10px;background-color:red"></div>
<script type="text/javascript">
var aa = {
a : 4,
b : function() {
alert(this.a);
},
c : function() {
this.bb=8;
document.getElementById("a").onclick=this.d;
},
d:function() {
alert(this);
alert(this.a);
alert(aa.a);
}
}
aa.c();
</script>
</body>
</html>能否在点击时d函数中的this是aa而不是点击的那个dom.
改成这样试试
ie只有ie9可以用 同等其他兼容的方法
<!doctype html>
<html>
<body>
<div id=a style="width:10px;height:10px;background-color:red"></div>
<script type="text/javascript">
var aa = {
a : 4,
b : function() {
alert(this.a);
},
c : function() {
this.bb=8;
var me=this;
document.getElementById("a").onclick=function(){
me.d();
}
},
d:function() {
alert(this);
alert(this.a);
alert(aa.a);
}
}
aa.c();
</script>
</body>
</html>
a : 4,
b : function() {
......
}
<!doctype html>
<html>
<body>
<div id=a style="width:10px;height:10px;background-color:red"></div>
<script type="text/javascript">
var aa = {
a : 4,
b : function() {
alert(this.a);
},
c : function() {
this.bb=8;
document.getElementById("a").onclick=(function(obj){return function(){obj.d();}})(this);
},
d:function() {
alert(this);
alert(this.a);
alert(aa.a);
}
}
aa.c();
</script>
</body>
</html>