this的指向的几种情况

在每一个函数中,都有一个内置的变量:this

大多数情况下,this存储的是当前函数的调用者

    this指向在定义时是不确定的,在不同的情况下,this指向是不一定相同的

1.全局函数下 this指向该window

function fn(){
             console.log(this);
         }
         fn();

2.匿名函数对象的方法中,this指向该对象 a.b.c.d() d中的this指向c

// 匿名函数
        var p = {
           name:"马老师",
           title:{
               name:"如意门掌门",
               skill:function(){
                   console.log("闪电五连鞭");
                   console.log(this); //指向title
               }
           }
        }
        p.title.skill();  //  闪电五连鞭
        console.log(p);  //p对象

3事件绑定中this 指向事件源

var btn = document.getElementById("btn")
        btn.onclick = function(){
            console.log(this);  //指向btn
        }

4定时器函数,this指向window setTimeout setInterval

setInterval(function(){
            console.log(this);
        },1000)

5构造函数 this指向实例化出来新的对象

function Person(name, age) {
    this.name = name;
    this.age = age;
}
var p = new Person(1,2) // this指向新创建的实例对象
经验分享 程序员 微信小程序 职场和发展