zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Spring+Mybatis整合
    Spring入门之生命周期
    异常处理
    淘淘商城第一天
    Maven的Setting配置
    mysql下载
    整合mybatis的CRUD4
    整合mybatis的CRUD3
    整合mybatis的CRUD2
    整合mybatis的CRUD
  • 原文地址:https://www.cnblogs.com/skura23/p/8409980.html
Copyright © 2011-2022 走看看