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
The
this
in the
foo
function is still{id:23}
, but whensetTimeout
is accepted and returned,this
becomeswindow
, so the global 0 is output. The second one is because Arrow function,this
is bound tothis
offoo2
, so it is 2The 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:
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