JS中this的指向

179 阅读1分钟

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); 
        console.log(cat2); 

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

    function Cat(name,color){
            this.name=name;
            this.color=color;
          }
       Cat("折耳","橘色");
       console.log(window.name)//折耳
       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)//折耳
    console.log(cat.color)//橘色

思考1

    let obj={
        x:  10,
        fn: function(){
                function a(){
                    console.log(this.x)
                }
                a();
            }
    };
    obj.fn() //输出什么?   
    结果为undefined obj.fn()调用时 a函数归属于window window下面没有x属性

思考2

    let obj={
        x:  10,
        fn: function(){
                console.log(this.x)
            }
    };
    let a=obj.fn;
    obj.fn() //输出什么?
    a(); //输出什么?
    obj.fn()调用时输出为obj.x的值为10
    a()调用时,window.a 输出为undefined

思考3

    let obj={
            x:  10,
            fn: function(){
                	return function (){
                        console.log(this.x)
                    }
                }
        };
    obj.fn()() //输出什么?
    输出为undefined  obj.fn()接收的是一个属于window的函数,所以指向window