this is not a dumb question! It's really important.
A method is a function that belongs to a class. It is invoked by specifying an object of that class, a dot, and the name of the method, and then its arguments.
If you've been coding in Java, it's easy to forget, because Java (as we know it) doesn't have functions; it only has methods.
However, newer versions of Java have added functions back in, partly because of the need for callback functions, which is exactly why we are learning them.
We use this
because that's how OOP works: we define
methods to operate on objects of different kinds. The code
for deposit
on a bank account can't know what bank
balance to increment. It operates on this
.
var hat = [10, 20, 30, 40]; // total of 100 hat.map(function (amt) { ron.deposit(amt) });"
Because the function doesn't refer to this
, so the
fact that this
has the wrong value doesn't cause trouble.
class Account { ... depositAll (hat) { console.log(this.balance); // works hat.map(function (amt) { this.deposit(amt) }); } ... }
The function above refers to this
, which has the wrong
value, and so disaster ensues.
But if we used an arrow function instead, all would be well.
Those are the rules for the invocation of ordinary functions. When
JS was created, Brendan Eich knew he wanted OOP and functions, and
that functions would refer to this
and
so this
had to be bound when invoking a
function.
So if we invoke a function inside a method, we have to take that into account.
Sure. Suppose we are doing two things:
.click
and .forEach
If we are doing both, we have to think for a minute before passing a method as an argument to a function: namely, what will the object be?
Sometimes, we need to use the .bind
method to specify the object.