> 文档中心 > JavaScript this指向

JavaScript this指向


定义

this是一个使用在作用域内部的关键字 ;

全局很少用,大部分在函数内部使用;

指向

全局使用: window

函数使用:不管函数怎么定义,不管函数在哪定义,只看函数的调用(箭头函数除外)

1、普通函数调用直接调用/全局调用

函数名() : this 指向 window

    function fn() {     console.log(this) } fn(); //普通调用 指向 window

2.定时器处理函数 :

setTimeout(function(){}, 0) this 指向 window

se'tInterval(function(){}, 0)    this 指向 window

function fn() {     console.log(this) } fn(); //普通调用 指向 window setTimeout(fn,0) // 定时器处理函数, this 指向 window

 

3.自执行函数

   (function (){})() this 指向  window           

4.对象函数调用:

  xxx.函数名()  : this 指向 点前面是谁就是谁

举例1:

  a.b.c(); //不管c前面有多少,c点前面都是

举例2: 

   function fn() {     console.log(this) } fn(); //普通调用 指向 window var obj = {     //把 fn 存储的地址赋值给了 obj 的 f成员      f: fn, } obj.f();  //对象调用, this 指向 obj

 

5.事件处理函数

xxx.onclick = function() {}  this 指向 事件源 (绑定在谁身上的事件)

xxx.addEventListener('', function(){})   this 指向 事件源

 function fn() {     console.log(this); }    //获取元素div var div = document.querySelector('div');    //点击div执行时执行函数  div.onclick = fn;   //this 指向事件源 div

 总结:不管函数怎么定义,不管函数在哪定义,只看函数的调用(箭头函数除外)