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

  • 相关阅读:
    问题 A: C#抽象类Vehicles
    最短路练习
    BFS
    poj 1083 Moving Tables
    组合数
    hdu 1443 Joseph【约瑟夫环】
    poj 2449 Remmarguts' Date【第K短路】
    hdu 1695 GCD 【莫比乌斯函数】
    hdu 2178 猜数字
    bzoj 2440 完全平方数 【莫比乌斯函数】
  • 原文地址:https://www.cnblogs.com/skura23/p/8409980.html
Copyright © 2011-2022 走看看