this指向

2019-08-21  本文已影响0人  Artifacts

1.在全局使用this

  console.log(this)//this指向window

2.函数中的this

  function show(){
    consloe.log(this);//window,谁调用,this就指向谁
  }
show()

3.事件绑定中的this

  var box = document.querySelector(".box")
          box.onclick = function(){
                console.log(this);  //box, 谁绑定事件,this就是谁
          }
  1. 事件绑定中,调用其它函数的this
   var box = document.querySelector(".box")
             function show(){
                 console.log(this);  //window,谁调用,this是谁
             }
             box.onclick = function () {
                console.log(this); //this指向box
                 show();
             }

5.定时器中的this: 无论定时器在哪出现,其内部的this都指window

  setInterval(function(){
                     console.log(this) //window
                 },3000)
  1. 构造函数和原型中的this
  //this指向new出来的新的实例化对象

改变this指向

上一篇 下一篇

猜你喜欢

热点阅读