浅谈 this 的一些指向问题

86 阅读1分钟
  1. 一般的几句话,谁调用函数,函数内部的this就指向谁,(this就是一个局部变量,函数调用的时候有系统自动创建,函数调用结束以后,自动销毁)
  2. 特殊的一个,构造函数,内部的this值和原型对象上面函数内部的this值就等于 new 出来的实例对象
  3. 箭头函数和普通函数的区别, 箭头函数内部没有this值,它的确定是在函数定义的位置,会自动查找定义位置的上一层作用域的this值。 普通函数是调用的时候决定的this值
  4. 定时器和延时器塞队列,最后是由window触发的,所以输出window

<body>
<button class="btn">練習</button>
 <script>
const btnDom = document.querySelector('.btn')
btnDom.addEventListener('click', function () {
  const p = () => {
    console.log(1, this);//点击事件触发this指向btndom(箭头函数内部没有this值,它的确定是在函数定义的位置,会自动查找定义位置的上一层作用域的this值)
  }
  p()
  console.log(this)//点击事件触发this指向btndom(函数调用的时候有系统自动创建,函数调用结束以后,自动销毁))
})


function fn() {
  console.log(this);//this指向对象为Window

}
fn()
 </script>
 </body>
<body>
    <script>
      var myName = 1;

var obj = {
  myName: 2,
  func: function () {
    console.log('16行:', this === obj);//this指向obj true
    return {
      myName: 3,
      getName1: () => {
        console.log('1行:', this);箭头函数 this指向上一级作用于所以 this指向obj
        console.log('2行', this.myName);//箭头函数 this指向上一级作用于所以 this指向obj myName为2
      },
      getName2: function() {
        console.log('3行:', this);//this指向a等于return返回的函数
        console.log('4行', this.myName);//myName=3
      },
    };
  },
};

const a = obj.func(); 
a.getName1()
a.getName2()


    </script>

</body>
    <script>
        var myName = 1;

        var o = {
            a: 10,
            b: {
                a: 12,
                fn: function () {
                    console.log(this);
                },
            },
        };
        // 如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象
        o.b.fn();//调用时 this指向 b
        const o2 = o.b.fn  
        o2()//this指向Window.o2

    </script>

</body>