javascript - 事件函数中this指向
问题描述

<!DOCTYPE HTML><html lang='en-US'><head> <meta charset='UTF-8'> <title></title></head><body><h2 onmousedown = 'f1(this)'>事件中的this</h2> <script type='text/javascript'>var h2 = document.getElementsByTagName(’h2’)[0];//HTML方式绑定function f1(obj){ console.log(obj);}f1( this );/*//DOM 0级绑定方式h2.onclick = function(){ console.log(this);}//DOM 2级方式h2.addEventListener(’mouseover’,function(){ console.log(this);});*/ </script> </body></html>
问题解答
回答1:javascript的this跟函数定义在哪里无关,跟谁调用它有关。
回答2:h2那里因为是绑定在事件上的,因此 this 指向的是这个元素,你可以简单理解为是
var dom = document.getElementsByTagName(’h2’)dom.onmousedown = function(){ f1(this)}回答3:
http://www.cnblogs.com/soulii...看看这个
回答4:前者相当于`请输入代码
var h2 = document.querySelectorAll('h2')[0];function fn(){ console.log(this);}h2.onmousedown = fn;window.fn();
this指向调用它的对象,你定义在全局环境里的变量和函数默认是window对象下得属性和方法,所以当你在全局环境中执行fn()时this指向window
回答5:你获取到哪个dom,就是对应的this。
回答6:这两个不是一回事呀。
<h2 onmousedown='f1(this)'></h2>h2.onmouseover=f1()h2.addEventListern(f1)
这三种方式都是为h2绑定了一个mouseover事件发生时的名为f1回调函数,事件绑定的回调函数指向DOM元素本身。
你问题中的
//HTML方式绑定function f1(obj){ console.log(obj);}f1( this );
这段程序是在window作用域下运行的,this自然就指向window。这段代码跟h2无关了(未绑定)。
相关文章:
1. debian - docker依赖的aufs-tools源码哪里可以找到啊?2. docker安装后出现Cannot connect to the Docker daemon.3. docker start -a dockername 老是卡住,什么情况?4. docker内创建jenkins访问另一个容器下的服务器问题5. docker镜像push报错6. nignx - docker内nginx 80端口被占用7. html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走3048. 为什么我ping不通我的docker容器呢???9. dockerfile - 为什么docker容器启动不了?10. 关于docker下的nginx压力测试

网公网安备