js this小记

在JavaScript中,this 对象是在函数被调用时动态定义的.

JS中有三种方法来设置this对象:

  1. someThing.someFunction(arg1, arg2, argN)
  2. someFunction.call(someThing, arg1, arg2, argN)
  3. someFunction.apply(someThing, [arg1, arg2, argN])

上面几个例子中, this 都是 someThing, 调用没有前导父对象的函数通常会得到全局对象,

在大多数浏览器中这个对象意味着窗口对象。

因此, 下面的代码会打印出两个window:

function a(){
    console.log(this, '是a的this')
    function b(){
        console.log(this, '是b的this')
    }
    b()
}
a()
// window,是a的this
// window,是b的this

 

故下面的代码会打印 c 和 window:

var c = {a: a}
function a(){
    console.log(this, '是a的this')
    function b(){
        console.log(this, '是b的this')
    }
    b()
}
c.a()
// c, 是a的this
// window, 是b的this

使用es6的箭头函数可避免无前导父对象的函数被调用时 this 指向 window 的问题,

它会将 this 设置为箭头函数被定义时所处的函数体的宿主对象, 下面会打印 c 和 c:

var c = {a: a}
function a(){
    console.log(this, '是a的this')
    var b = ()=>console.log(this)
    b()
}
c.a()
// c, 是a的this
// c, 是b的this

关于更进一步理解es6的箭头函数的 this, 这篇博客写的不错可以看看:

http://blog.csdn.net/u013344815/article/details/73184928#insertcode

 

转载于:https://www.cnblogs.com/skura23/p/8409980.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值