js this指向

1. 全局作用域或者普通函数中this指向全局对象window(注意定时器里面的this指向window)
2. 方法调用中谁调用this指向谁
3. 构造函数中this指向构造函数的实例

JS中this的指向

1.当函数作为构造函数,通过new xxx()调用时,this指向生成的实例

    function Cat(name,color){
            this.name=name;
            this.color=color;
          }
        let cat1 = new Cat("大毛","橘色");//this指向的cat1
        let cat2 = new Cat("二毛","黑色");//this指向的cat2
        console.log(cat1);   //指向实例cat1
        console.log(cat2); 

2.当函数直接被调用时(通过 xxx()的方式调用)this指向window对象,严格模式下为undefined

    function Cat(name,color){
            this.name=name;
            this.color=color;
          }
       Cat("大毛","橘色");
       console.log(window.name)//大毛  //this指向window
       console.log(window.color)//橘色

3.当函数被调用时,它是作为某个对象的方法(前面加了 点'.')this指向这个对象(点'.'前面的对象)(谁调用它,它就指向谁)

    function setDetails(name,color){
                this.name=name;
                this.color=color;
              }
    let cat={};
    cat.setDetails=setDetails;
    cat.setDetails('大毛','橘色');
    console.log(cat.name)//大毛   //指向cat
    console.log(cat.color)//橘色

思考1

    let obj={
        x:  10,
        fn: function(){
                function a(){
                    console.log(this.x)
                }
                a();
            }
    };
    obj.fn() //输出什么?  window  undefind  this指向window找不到上面的x,可以打印尝试

思考2

    let obj={
        x:  10,
        fn: function(){
                console.log(this.x)
            }
    };
    let a=obj.fn;
    obj.fn() //输出什么?   10  obj  this指向obj,可以打印出obj.x
    a(); //输出什么?       window undefind  相当于a:function(){console.log(this.x)} ,找不到x

思考3

    let obj={
            x:  10,
            fn: function(){
                	return function (){
                        console.log(this.x)
                    }
                }
        };
    obj.fn()() //输出什么?  window undefined
原文地址:https://www.cnblogs.com/xm0328/p/13976492.html