The 5 rules of this
Priority order — first match wins.
new—this= fresh object. Highest priority.- Explicit binding —
fn.call/apply/bind(obj)→this=obj. - Implicit binding —
obj.fn()→this=obj(object before the dot). - Default binding — standalone
fn()→window(non-strict) orundefined(strict). - Arrow function — no own
this; inherits from enclosing lexical scope; cannot be overridden.
call / apply / bind
Solve the 'lost this' problem.
- call:
fn.call(ctx, a, b)— invoke NOW with comma-separated args. - apply:
fn.apply(ctx, [a, b])— invoke NOW with args in an array. Pre-ES6 workaround for spreading. - bind:
fn.bind(ctx, a)— returns a NEW function withthislocked forever. Supports partial application. - bind is permanent — call/apply/second bind cannot override. Only
newwins over bind.
Currying
f(a,b,c) becomes f(a)(b)(c).
- Transforms multi-arg functions into a sequence of single-arg functions.
- Enables partial application — lock some args now, supply the rest later. Creates specialized tools from general ones.
- Generic curry: collect args; when
args.length >= fn.length, call the original; otherwise return a collector. - Infinite currying:
sum(a)returns a function; if called with a value, recurse withsum(a + b); empty call returns accumulated total.
Promise states & chaining
Three states, one settlement.
- States: Pending → Fulfilled (resolve) or Rejected (reject). Settlement is permanent and immutable.
- Executor runs synchronously.
resolve()does NOT stop executor code — lines after it still run. .thenreturns a new promise → chainable. Return a value → next .then gets it. Return a promise → chain waits.- One
.catchat the end catches errors from any step above — like try/catch wrapped around the chain.
The 4 static methods
Combine multiple promises.
- Promise.all — ALL succeed → array of results in input order. First reject → fails immediately.
- Promise.allSettled — wait for ALL to finish. Never rejects. Returns
{status, value/reason}per promise. - Promise.race — first to SETTLE wins (success OR failure). Used for timeout patterns.
- Promise.any — first to SUCCEED wins. Rejects only if ALL fail (AggregateError with
.errors).
async / await
Sugar over promises.
asyncfunction always returns a promise (plain values auto-wrapped; existing promises returned as-is).awaitpauses the function (not the engine); function is suspended, popped off stack, resumed via microtask.- Promises start at creation, not at await — creating two timers upfront means both tick in parallel.
- Errors:
try/catchinside async (recommended) or.catch()on the function call.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.