五种this的详解

在 new fn() 调用中,fn 里的 this 指向新生成的对象,这是 new 决定的
在 fn() 调用中, this 默认指向 window,这是浏览器决定的
在 obj.fn() 调用中, this 默认指向 obj,这是 JS 的隐式传 this
在 fn.call(xxx) 调用中,this 就是 xxx,这是开发者通过 call 显式指定的 this
在 arrow() 调用中,arrow 里面的 this 就是 arrow 外面的 this,因为箭头函数里面没有自己的 this
在 arrow.call(xxx) 调用中,arrow 里面的 this 还是 arrow 外面的 this,因为箭头函数里面没有自己的 this

1、window

// 第一种:this 指的就是 window
function fn() {
    console.log(this);
};
console.log(this);

2、事件中的this

// 第二种:所有事件函数中的this,都是这个监听事件监听对象
//在事件函数中 this===e.currentTarget 也就是事件侦听的对象。
//在事件中使用this,其实事件函数内部实现极力就是使用call等将事件中的this改为 e.currentTarget。
// currentTarget始终是监听事件者,而target是事件的真正发出者。
document.querySelector(".div0").onclick=function (e) {
    console.log(this);
    console.log(e.target);
    console.log(e.currentTarget);
};

3、对象中的this

// 第三种:对象中的this,this就是当前这个对象。
// 在对象的函数中,如果需要调用当前对象的其他函数或者属性时,必须加 this.属性名 或者 this.方法名.
var obj={
    a:1,
    c:function () {
        console.log(this.a);
    }
};

4、面向对象中的this

// 第四种:面向对象中的this
// ES5 面向对象写法
function Box(d) {
    this.d=d;
}
Box.prototype={
    a:1,
    c:function () {
	    //  这里的this就是box1
        console.log(this.a+this.d);
    }
};
var box1=new Box(10);
box1.c();

// ES6 的面向对象写法
class Ball{
    constructor(d){
        this.d=d;
        this.a=1;
    }
    c(){
        console.log(this.d+this.a)
    }
}

var ball1=new Ball(10);
ball1.c();

5、call,apply和bind中的this

//第五种:call,apply和bind中的this
// 这里的this就是被替换的对象
function fn2(a,b) {
    this.a=a;
    this.b=b;
    return this;
}

var obj1=fn2.call({},3,5);
var obj2=fn2.call({c:6},10,12);
console.log(obj1,obj2);// {a:3,b:5}, {a:3,b:5,c:6}

e.target和this的区别

// 常见事件对象的属性和方法
        // 1. e.target 返回的是触发事件的对象(元素)  this 返回的是绑定事件的对象(元素)
        // 区别 : e.target 点击了那个元素,就返回那个元素 this 那个元素绑定了这个点击事件,那么就返回谁
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) {
                // ul 绑定了事件  this 指向ul  
                console.log(this);
                console.log(e.currentTarget);

                // e.target 指向点击的对象 li触发了这个事件 e.target 指向的就是li
                console.log(e.target);

            })
            // 兼容性
            // div.onclick = function(e) {
            //     e = e || window.event;
            //     var target = e.target || e.srcElement;
            //     console.log(target);

        // }
        // 2.  this 有个非常相似的属性:currentTarget  ie678不认识
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Supernova_gu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值