Understanding By Example
Functions:
# Function Context Cheatsheet
## Types of Invocation
- Applies to only **named** and **unnamed** functions
- **Doesn't matter** for fat arrow functions
### Function-style invocation
- Context of the function will be global context **UNLESS** binded
### Method-style invocation
- Context of the function will be the object which the function is called on **UNLESS** binded
```javascript
const obj = {
name: 'Example Object',
unnamedFunc: function() {
console.log(this.name);
}
};
// Method-style invocation
obj.unnamedFunc(); // 'Example Object'
// Function-style invocation
const unnamedFunc = obj.unnamedFunc;
unnamedFunc(); // Global contextTypes of Functions
Named Function
explicit
returnkeyword requiredcurly braces
{}around function bodyNOT saved to a variable
parameters must be surrounded by parentheses
()context is defined by how it's invoked or called
function-style: global context
method-style: context is object that function is being called on
calling
bindon the function will return a function binded to the context of thebindargument
Unnamed Function
explicit
returnkeyword requiredcurly braces
{}around function bodyMUST be saved to a variable
parameters must be surrounded by parentheses
()context is defined by how it's invoked or called
function-style: global context
method-style: context is object that function is being called on
calling
bindon the function will return a function binded to the context of thebindargument
Explicit Fat Arrow Function
explicit
returnkeyword requiredcurly braces
{}around function bodyMUST be saved to a variable
parameters must be surrounded by parentheses
()IF more than one parametertakes the context of where it's defined
CANNOT be binded using
bind
Implicit Fat Arrow Function
NO
returnkeywordfunction body can only consist of what is being returned
Optional parentheses
()around function bodyNOTE: Parentheses needs to be used if returning an object
ex: ({ key: value })MUST be saved to a variable
parameters must be surrounded by parentheses
()IF more than one parametertakes the context of where it's defined
CANNOT be binded using
bind
Bind
bindaccepts multiple argumentsfirst argument is the context that you want to bind the function to
any arguments that come afterwards will be passed in when the bound function is called BEFORE the call time arguments
```
Scope:
Closure
Context:
Last updated
Was this helpful?