this的不同应用场景如何取值?

本文详细探讨了JavaScript中this的取值情况,包括在普通函数、call/apply/bind的使用、对象方法、箭头函数以及在class方法中的应用。重点阐述了this的确定时机以及不同场景下的变化,帮助读者理解JavaScript中this的动态特性。

使用场景

作为普通函数
使用call apply bind
作为对象方法被调用
箭头函数
在class方法在中被调用

this取什么值是在函数执行的时候确定的,不是在函数定义的时候确定的

function fn1() {
    console.log(this)
}
fn1()//window

fn1.call({x:100})//{x:100}

const fn2 = fn1.bind({X:200})
fn2()//{x:200}
const zhangsan ={
    name: '张三',
    sayHi() {
        //this即当前对象
        console.log(this)
    },
    wait() {
        setTimeout(function() {
            //this === window
            console.log(this)
        });
    }
}

箭头函数取值取上级作用域的值

const zhangsan ={
    name: '张三',
    sayHi() {
        //this即当前对象
        console.log(this)
    },
    wait() {
        setTimeout(() => {
            //this即当前对象
            console.log(this)
        });
    }
}
class People {
    constructor(name) {
        this.name = name;
    }
    sayHi() {
        console.log(this)
    }
}
const zhangsan = new People('张三');
zhangsan.sayHi();//zhangsan对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值