Javascript之this指向

变换莫测的this指向

  • 事件调用环境
    谁触发事件,函数里面的this就指向谁

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
    .box{
    width: 100px;
    height: 100px;
    background: #0A8CD2;
    left: 0;
    transition: 1s;
    position: relative;
    }
    </style>
    </head>
    <body>
    <div class="box"></div>
    <script>
    let box = document.querySelector('.box');
    box.onclick = move;
    function move(){
    this.style.left = '100px';
    }

    console.log(this);
    </script>
    </body>
    </html>
  • 全局环境

    如上所示全局环境下在浏览器中的this指向window。
    在Node环境中如下图所示

    this_node