How it works
The explanation, with examples you can run.
Four ways to call a function
- With new:
new User()creates an object and passes it asthis. - Explicitly:
fn.call(x),fn.apply(x)andfn.bind(x)choosethisyourself. A bound function keeps it for good. - As a method:
obj.fn()passesobj. It is the dot at the moment of the call that counts, not where the function was defined. - Plainly:
fn()passesundefinedin strict code. In old sloppy-mode scripts it falls back to the global object, which hides the bug.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Arrow functions
An arrow function does not get a this from its call. It uses the this of the code it sits in. That makes it the right choice for callbacks inside methods, and the wrong choice for a method itself: an arrow written as an object property sees the this of the surrounding code, not the object.
Press Run to see what your code prints, in order.
Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.
Check yourself
2 questions. Get them all right to finish this topic.
0 of 2 right so far. Get all two to finish this topic.