zoukankan      html  css  js  c++  java
  • 1.7 this关键字

    JS中主要研究的都是函数中的this

    JS中的this代表的是当前行为执行的主体;JS中的context代表的是当前行为执行的环境(区域);

    this是谁和函数在哪定义的和在哪执行的都没有任何的关系:如何区分this呢?

      1. 函数执行,首先看函数名前面是否有“.”,有的话,“.”前面是谁this就是谁,没有的话this就是window

    function fn () {
      console.log(this)
    }
    var obj = {fn:fn};
    fn(); // this->window
    obj.fn(); //this->obj
    function sum () {
      fn(); // this->window
    }
    sum()
    var oo = {
    sum: function () {
      // this ->oo
    fn(); // this->window
     }
    }
    oo.sum();

      2. 自执行函数中的this永远是window

      3. 给元素的某一个事件绑定方法,当事件触发的时候,执行对应得方法,方法中的this是当前的元素

    <div id="div1"></div>
    function fn () {
      console.log(this)
    }
    document.getElementById("div1").onclick = fn;// fn中的this是div1
    document.getElementById("div1").onclick = function () {
    // this -> #div1 fn();
    //this ->window }

       4.在构造函数模式中,类中(函数体中)出现的this.xxx = xxx 中的this是当前类的一个实例

      5.call,applay,bind改变this指向(一但遇到call/apply上述的四条都没用了)

  • 相关阅读:
    事物的五种传播机制与七种传播行为
    Spring jdbcTemplate
    SpriingMVC执行流程结构
    SpringMVC视图解析器
    promise的基本使用和理解
    集合set的类型转换
    数据结构小结一
    Dotween的一些常用方法记录
    线程与进程的解释
    反射和特性
  • 原文地址:https://www.cnblogs.com/z-dl/p/8717331.html
Copyright © 2011-2022 走看看