Home  >  Q&A  >  body text

javascript - A problem with js call, very simple code, how to interpret the output result?

foo2() uses the arrow function.
According to the understanding of call, foo.call({id:23}) should output 23, not 0. So, can anyone explain this?
The code is as follows:
<script type="text/javascript">

    function foo() {
        setTimeout(function (){
            console.log('id1:', this.id);
        }, 100);
    }
    
    function foo2() {
        setTimeout(() => {
            console.log('id2:', this.id);
        }, 100);
    }
    
    var id = 0;
    foo.call({id:23});
    foo2.call({id: 2});

</script>

Execution result:
0
2

phpcn_u1582phpcn_u15822648 days ago684

reply all(6)I'll reply

  • 迷茫

    迷茫2017-06-26 10:52:10

    The

    this in the foo function is still {id:23}, but when setTimeout is accepted and returned, this becomes window, so the global 0 is output. The second one is because Arrow function, this is bound to this of foo2, so it is 2

    reply
    0
  • typecho

    typecho2017-06-26 10:52:10

    The parameter of setTimeout of foo2 is an arrow function, and this inside it is the scope where the binding definition is (when foo2 is executed, this is the object in the call), rather than pointing to the scope where the runtime is. The functions in ordinary setTimeout are bound to the runtime scope (window).

    reply
    0
  • 代言

    代言2017-06-26 10:52:10

    1. The this of the foo function is window, and the this of the foo2 function is the object {id: 2}.

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-26 10:52:10

    Obviously, the first this points to window, and the second arrow function this points to the current object, which means whoever calls it points to whoever calls it;
    The first one can be changed to solve the problem:

        function foo() {
            var _this = this;
            setTimeout(function (){
                console.log('id1:', _this.id);
            }, 100);
        }
        var id = 0;
        foo.call({id:23});

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-06-26 10:52:10

    1. The callback function in setTimeout is executed 100ms after foo is executed, and the runtime scope is window.
    2. The arrow function allows this in setTimeout to be bound to the scope where it is defined, rather than pointing to the scope where it is run.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-26 10:52:10

    The problem of arrow function scope

    reply
    0
  • Cancelreply