this的初步理解

函数中的this
1.函数中的this,表示当前行为执行的主体
2.上下文context表示当前行为执行的环境或区域
3.主体和环境相互不影响. eg:在公司,花花拖地 和 在家,花花拖地 花花是拖地行为执行的主体,在哪属于环境,
4.如何区分this
  1.函数执行,函数名前面有没有点,如有点则this就是点前面的东西,反之this是window
  2.自执行函数的this永远是window
  3.给元素某个事件绑定方法,事件触发的时候,执行对应的方法,方法中的this指当前元素

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <script>
  function fn() {
    console.log(this);
  }
  var obj = {
    fn:fn
  };
  obj.fn(); // 点前面是obj,this指obj
  fn(); // 没点 ,this指window, 其实因为全局对象window,相当于window.fn()


  // 自执行函数,this指window
  ~ function() {
    console.log(this)
  }();
  // this指document
  document.onclick = fn;
  // fn里的this是window,前面没有点
  document.onmouseover = function() {
    fn();
  }
  </script>
</body>

</html>

点击查看详情

原文地址:https://www.cnblogs.com/2han/p/6273526.html