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

 

posted @ 2018-02-03 17:07  PajamaCat  阅读(146)  评论(0编辑  收藏  举报