this

143 阅读1分钟

1、ES5全局this

  this.a=3;//this--->window
  var b=5;
  function fn(){
      var b=10;
      console.log(b+this.b);//this--->window
      // 这种方法仅限于ES5,在ES6严格模式中this将会变成undefined
  }

  fn();

2、数组的所有遍历方法--->作为回调函数,其中的函数都是在外部被调用的

数组的所有遍历方法forEach,map,filter,reduce,every,some,flatMap,sort 这些方法均使用了回调函数,因此在所有使用回调函数的方法中,除了特殊的情况外(事件函数),其他所有回调函数中this都被指向window,setInterval,setTimeOut

3、对象中this

    var c=100;
    var obj={
        c:10,
        b:this.c,//this--->window  定义属性时,obj对象还没有创建完成,this仍旧指向window
        a:function(){
            // this;//this--->obj  对象创建完以后运行的
            // console.log(obj.c);
            console.log(this.c);
        },
        d:()=>{
            //this--->window
            console.log(this);
        }
    }

4、class中的this

    class Box{
        a=3;
        static abc(){
            console.log(this);//Box  静态方法调用就是通过类名.方法
            // Box.abc();
            // 尽量不要在静态方法中使用this
        }
        constructor(_a){
            this.a=_a;
        }
        play(){
            // this就是实例化的对象
            console.log(this.a);
            // 这个方法是被谁执行的,this就是谁
        }
    }

5、ES5 类中的this

    function Box(_a){
        this.a=_a;
    }
    Box.prototype.play=function(){
        console.log(this.a);//this就是实例化的对象
    }
    Box.prototype.a=5;
    Box.abc=function(){
        //this
        // 这样的方法,等同于静态方法
    }

6、事件函数中this

    document.addEventListener("click",clickHandler);
    function clickHandler(e){
        console.log(this);//this--->e.currentTarget
    }

7、call apply bind

        function fn(a,b){
            this.a=a;//this如果使用了call,apply,bind,this将会被指向被绑定的对象
            this.b=b;
            return this;
        }

        var obj=fn.call({},3,5)
        var obj=fn.apply({},[3,5])
        var obj=fn.bind({})(3,5);

8、 箭头函数

var obj={
    a:function(){
        document.addEventListener("click",e=>{
            console.log(this);//指向事件侦听外函数中的this/obj
        });
        var arr=[1,2,3];
        arr.forEach(item=>{
            console.log(this);//this-->obj
        });
        // 相当于自带bind(this)的作用
        arr.forEach((function(item){

        }).bind(this));
    }
}