javascript - A problem with js call, very simple code, how to interpret the output result?
phpcn_u1582
phpcn_u1582 2017-06-26 10:50:10
0
6
680

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_u1582
phpcn_u1582

reply all(6)
迷茫

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

typecho

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).

代言

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

巴扎黑

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});
曾经蜡笔没有小新

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.

伊谢尔伦

The problem of arrow function scope

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!