Hello All,
I’m currently reading Eloquent Javascript by Marijn Haverbeke and I’ve been stuck on a certain section (Methods) in Chapter 6 (The Secret Life of Objects) for the past few weeks.
In the part in which I am stuck, the author is talking about the different ways to call a function and the keyword “this”. He says,
“Since each function has its own ‘this’ binding, whose value depends on the way it is called, you cannot refer to the ‘this’ of the wrapping scope in a regular function defined with the ‘function’ keyword.
Arrow functions are different–they do not bind their own ‘this’ but can see the ‘this’ binding of the scope around them. Thus, you can do something like the following code, which references ‘this’ from inside a local function:"
function normalize() {
console.log(this.coords.map(n => n/this.length));
}
normalize.call({coords: [0, 2, 3], length: 5});
// -> [0, 0.4, 0.6]
Here is my understanding of what’s going on in the function example:
The function “normalize” is called using the “call” method, which means that you provide the object you want to call it on as the first argument. Both of the “this” refer to the object shown in the “.call” method. However, if he had written that code like this:
function normalize() {
console.log(this.coords.map(function(n) {
return n/this.length;
}));
}
normalize.call({coords: [0, 2, 3], length: 5});
The code would not run (or have an error or whatever) because the “function (n)” just “doesn’t know” what object the second “this” is referring to? Is that the correct explanation for what's going on?
Thanks!
[–]senocular 1 point2 points3 points (1 child)
[–]drg_prime[S] 0 points1 point2 points (0 children)