JS(ES6)中this的四种用法

转载文章:https://www.cnblogs.com/pabitel/p/5922511.html

JS(ES6)中this的五种用法

1.在回调函数中使用this 不知道调用者是谁?

//setInterval定时器函数中的回调函数,不知道最后是那个在调用,如果回调函数不用箭头函,那this就不知道是谁?
let startObj = {
    init:function(){
        setInterval(() => {
            console.log(this); //因为是箭头函数,所以这里的this和init()函数的this一致,指向startObj对象;
        },1000)
    },

    initx: function() {
        console.log(this);//这里的this直接指向startObj对象;
    }
}
startObj.init();
startObj.initx();

首先讲js中最特殊也是最容易犯错的一种,回调函数中的this,回调函数属于异步函数,你不知道最后是谁在调用它,所以this很容易犯错!那么在回调函数中,我们可以使用箭头函数()=> {}  ,因为箭头函数不绑定this,永远和上一个封闭函数中的this保持一致!

1.在一般函数方法中使用 this 指代全局对象

function test(){    
    this.x = 1;    
    alert(this.x);  
}  test(); // 1

2.作为对象方法调用,this 指代上级对象

function test(){
  alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1

3.作为构造函数调用,this 指代new 出的对象

  function test(){
    this.x = 1;
  }
  var o = new test();
  alert(o.x); // 1
    //运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:
  var x = 2;
  function test(){
    this.x = 1;
  }
  var o = new test();
  alert(x); //2

4.apply 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数

  var x = 0;
  function test(){
    alert(this.x);
  }
  var o={};
  o.x = 1;
  o.m = test;
  o.m.apply(); //0
//apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。如果把最后一行代码修改为

  o.m.apply(o); //1

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/85775521
今日推荐