前端修改this指向及修改this指向

  一、this指向问题

1.普通函数调用,此时 this 指向 window

  function fn() {

    console.log(this); // window

  } fn();

   // window.fn(),此处默认省略window

2.构造函数调用, 此时 this 指向 实例对象

  function Person(age, name) {
    this.age = age;
    this.name = name
    console.log(this) // 此处 this 分别指向 Person 的实例对象 p1 p2
  }
  var p1 = new Person(18, 'zs')
  var p2 = new Person(18, 'ww')

3.对象方法调用, 此时 this 指向 该方法所属的对象

  var obj = {

    fn: function () {

      console.log(this); // obj

     } }

  obj.fn();

4.通过事件绑定的方法, 此时 this 指向 绑定事件的对象

  

<body>
<button id="btn">hh</button>
<script>
var oBtn = document.getElementById("btn");
oBtn.onclick = function() {
console.log(this); // btn
}
</script>
</body>

5.定时器函数, 此时 this 指向 window

  setInterval(function () { console.log(this); // window }, 1000);

  二、修改this指向

1.call() 方法

  

  var Person = {
    name:"lixue",
    age:21
  }
  function fn(x,y){
    console.log(x+","+y);
    console.log(this);
  }
  fn("hh",20);

普通函数的this指向window,

  var Person = {
    name:"lixue",
    age:21
  }
   function fn(x,y){
    console.log(x+","+y);
    console.log(this);
    console.log(this.name);
    console.log(this.age);
  }
  fn.call(Person,"hh",20);

现在this就指向person了

2.apply()

  apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表

3.bind()

  bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上

案例:

  一、

  var oDiv1 = document.getElementById("div1");
  oDiv1.onclick = function(){
    setTimeout(function(){
    console.log(this);

  },1000)
  }  

  二、

  var oDiv1 = document.getElementById("div1");
  oDiv1.onclick = function(){
    setTimeout(function(){
      console.log(this);
    }.bind(this),1000)
  }

因为在定时器外,在绑定事件中的this肯定指向绑定事件的对象div啊,用call和apply都行

上图就是用bind改变了this指向,但改变定时器中的this指向,我们有个更好的方法

posted @ 2021-04-06 09:25  web格调  阅读(465)  评论(0编辑  收藏  举报