JavaScript中this详解

在JavaScript中很多人对this的指向不是很明白,在这里对这个知识点进行一下总结。

总的来说this的指向分为以下四种情况:

1.全局作用域或者普通函数this的指向是window

Example:
//全局作用域
console.log(this); //指向window       

//普通函数
function a(){
            console.log(this); 
        }
        a(); //指向widow 

2.有事件源的指向事件源本身

document.onclick(){
    console.log(this); //this指向document
}
需要注意的是下面这种情况:
document.onclick(){
    function a(){
        console.log(this);
    }
    a();  //指向window 因为a()属于普通函数
}

3.在定时器下除es6的箭头函数外,this指向window

document.onclick = function () {
    function a() {
         console.log(this);
     }
     a(); //window
    }


//在es6的箭头函数下this指向的是最靠近它的父级
document.onclick(){
    setInterval(()=>{
        console.log(this); //this指向setInterval的父级document
    },100);
}

4.在对象(什么是对象)下,this指向的是本身

var json = {
    a:function(){
        console.log(this);//object 也就是json
    }
}


//构造函数为例
function animal(name){
    this.name = name;
    console.log(this); //指向windos
}
animal("dog"); //windos 

function animal(name){
    this.name = name;
    console.log(this);//指向animal
}
//对象实例化后改变了this的指向,由原本指向window改为指向animal
var ani = new animal("dog");

以上是我对this的一些简单的理解,如有错误的地方,希望能够指出来。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值