this指向问题

87 阅读1分钟

this呢,是函数的内置对象,所以,this只能出现在函数里

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

    function fn() {
       console.log(this);   // window
     }
     fn();  //  window.fn(),此处默认省略window

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

        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指向window