On this page
Functions, Closures & this
Prev: Core Syntax & Types | Up: tutorials | Next: Prototype Chain & new Instantiation Flow
Rel: Prototype Chain & new Instantiation Flow, Events & Delegation
Ref: MDN Web Docs — Closures
Tags: #public #web #javascript #tutorials #functions
Contents
Lexical Scope & Closures
A closure is a function paired with its lexical environment, retaining live access to outer variables after the enclosing function returns:
function makeCounter(start = 0) {
let count = start;
return (step = 1) => (count += step);
}
const next = makeCounter(10);
console.log(next(), next(5)); // 11 16
The Four this Binding Rules
For regular (non-arrow) functions, this is determined at call time, in descending precedence:
newbinding:new Foo()bindsthisto the newly created object.- Explicit binding:
fn.call(ctx, a, b),fn.apply(ctx, [a, b]), orfn.bind(ctx). - Implicit (method) binding:
obj.method()bindsthistoobj(detachedconst m = obj.method; m()losesobj). - Default binding:
undefinedin strict mode / ES Modules, orglobalThisin sloppy mode.
Arrow Functions vs. Regular Functions
Arrow functions ((x) => x * 2) have no own this, arguments, or [[Construct]] — they capture this lexically from their enclosing scope, making them ideal for callbacks and event listeners inside methods.
Linked from
Related notes
- tuts/javascript/tutorials Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/core_syntax_and_types Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/prototype_chain_and_new_flow Linked here; links to this page; shared tags: #javascript, #tutorials, #web
- tuts/web/dom/events_and_delegation Linked here; links to this page; shared tags: #web
- tuts/web/dom links to this page; shared tags: #web
- tuts/javascript/tutorials/event_loop_and_async_programming shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/iterators_and_generators shared tags: #javascript, #tutorials, #web
- tuts/javascript/tutorials/modules_and_error_handling shared tags: #javascript, #tutorials, #web
- tuts/css/functions shared tags: #functions, #web
- tuts/css/functions/color shared tags: #functions, #web