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. dockerfile - [docker build image失败- npm install]2. node.js - mongoDB使用$gte的问题3. java中关于直接插入排序遇到的问题。4. docker gitlab 如何git clone?5. javascript - c#如何向js传值6. angular.js - angular内容过长展开收起效果7. java - mybatis怎么实现在数据库中有就修改,没有就添加8. node.js - nodejs和前端JavaScript 字符串处理结果不一样是什么原因?9. nignx - docker内nginx 80端口被占用10. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?
![dockerfile - [docker build image失败- npm install]](http://www.haobala.com/attached/image/news/202311/1028105a80.png)