A function is an object
- it’s a value that can be used like any other value.
a function can be returned from a function:
A function can be passed to another function as an argument:
A function can be assigned to an object:
When a function is assigned to an object, when the implicit this keyword is accessed within that function it will refer to the object on which the function was called. This is why obj.fn() outputs 999.
this refers to the object on which the function was called, not the object which the function was assigned to:
Both obj and obj2 reference the same function but on each invocation the this context changes to the object on which that function was called.
Functions have a call method that can be used to set their this context:
In this case the fn function wasn’t assigned to any of the objects, this was set dynamically via the call function.
There are also fat arrow functions, also known as lambda functions:
When defined without curly braces, the expression following the fat arrow (⇒) is the return value of the function. Lambda functions do not have their own this context, when this is referenced inside a function, it refers to the this of the nearest parent non-lambda function.
While normal functions have a prototype property (which will be discussed in detail shortly), fat arrow functions do not: