There is no this binding in the
arrow function, and its value must be determined by looking for scope. Simply put, this binds the this of the nearest non-arrow function. The this of the arrow function in
1 and test1
points to the this bound within the test1
function, that is, the outer layer of the arrow function in obj
2 and test2
is still the outer layer of the arrow function. We have to find the outer layer of obj
, that is, the outer layer of the arrow function in window
3, test3
is the outer layer of obj
, that is, window
is actually the same as test3. No matter how many layers of arrow functions are embedded in the method, the main thing to make clear is that test1,test2,test3 is a first-class method of obj, and then there is the outside of obj, not inside of obj.
I don't know how to interpret this sentence, but it must be the runtime that determines the value of this
. (this has nothing to do with the arrow function)
let test = function() {
console.log(this)
}
test();//window
let obj = { test }
obj.test();//obj
The
arrow function does not create its own this
, it only inherits this
from one layer above its scope chain.
this
in several cases:
-
new
, pointing to the new object.
-
bind/apply/call
, point to the first parameter (or window
if the first parameter is null
).
- points to the object as a method call to the object.
The - function call points to
window
.
Please re-check your this
against the above rules. In addition, numerous articles on the site have introduced this
, please search by yourself.
the arrow function has already determined the direction before it runs. Without this, the one bound is the this of the nearest non-arrow function.
test4: function () {
console.log("test4", this);
}//obj
assuming that it is a normal function, this points to obj, because there is no arrow function and no binding, so look for the next layer is window
this rule seems ambiguous. The
arrow function does not have this
, and the this
value changes from parent scope -- grandfather scope --. Go all the way up to the global scope . (can be regarded as the search order of variables)
this
printed in
test1 is equivalent to this
in parent scope test1. this
printed in
test2 and test3 is equivalent to this
in the global scope found all the way up.
it's all in the picture