JS&ES6的this指向问题

JS&ES6的this指向问题

普通函数

  • 普通函数this——用于访问当前方法所属的对象
  • 普通函数的this跟定义无关,跟调用有关
//写法1
let obj = {
    a: 12,
    fn() {
        consolse.log(this == obj)
    }
}
obj.fn()
//结果:true

//写法2 直接写和后添加的方法是一样的
let obj = {
    a: 12,
    //fn() {
     //   consolse.log(this == obj)
    //}
}
obj.fn = function() {
	console.log(this == obj)
}
obj.fn()
//结果:true

//事件写法
document.onclick = function() {
    consolse.log(this == doucument)
}
//结果:true

------------------------------------------------------------------------------

//1-直接调用——windos|undefine(严格模式)
function show() {
    console.log(this)
}
show();

//2-挂载对象上,然后执行方法——this指向对象
let arr=[1, 2, 3]
arr.fn = show
arr.fn()


//3-定时器——this指向window
setTimeout(show, 100)

//4-构造函数(new)——当前构建出来的实例show{}
new show()

//5-工具函数,强制规定this的值
show.call(11)      //this为  11
show.call('sssd')  //this为  ’sssd‘
show.call({a: 12}) //this为   {a: 12}

//6-forEach,结果为window|undefine
arr.forEach(function() {
    console.log(this, item)
})

//forEach的第二个参数可以强制改变this的指向
arr.forEach(function() {
    console.log(this, item)
}, "强制改变的this")

箭头函数

  • 普通函数——function this取决于调用,this不固定
  • 箭头函数—— => this取决于定义,定义完成则不会改变,取决于定义时当前环境的this
let obj = {
    a: 12,
    //箭头函数
    () => {
        consolse.log(this == obj)
    }
}
obj.fn()
//false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值