JavaScript Reference ยท Classes and Modules
Scope and this
Concept page on JavaScript scope and this: the scope chain, block and function scope, shadowing, and the rules that decide what this refers to in each call.
Two ideas control how names and objects are found in JavaScript. Scope decides which variables a piece of code can see; it is fixed by where the code is written. this decides which object a function works on; it is mostly fixed by how the function is called. Mixing them up is the most common source of confusion, so it helps to keep them apart: scope is about the text of the program, this is about the call.
const label = "outer"; // scope: found by looking outward const user = { label: "user", show() { return this.label; }, // this: found from how show is called };
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Scope
Kinds of scope
- Global scope. Names declared at the top level of a classic script.
varand function declarations there also become properties of the global object;let,constandclassdo not. In an ES module, top-level names are local to the module. - Function scope. Parameters,
varvariables and inner function declarations belong to the function that contains them. - Block scope.
let,constandclassdeclarations belong to the nearest{ }block (includingif,forandcatchblocks).varignores blocks. - Module scope. Each ES module has its own top-level scope.
The scope chain
When code uses a name, the engine looks in the current scope, then in each enclosing scope, until it reaches the global scope. If nothing matches, you get a ReferenceError (reading) or, in sloppy mode, a new global (assigning). An inner declaration with the same name shadows the outer one.
Closures and hoisting
A function keeps a reference to the scope where it was created, so it can use those variables later; this is a closure. Declarations are processed before code runs: var is hoisted and starts as undefined, function declarations are hoisted whole, and let, const and class exist but are in the temporal dead zone until their line runs, so reading them early throws.
How this is bound
For ordinary functions, this is set at call time. In order of strength:
new f():thisis the freshly created object.f.call(obj),f.apply(obj),f.bind(obj):thisisobj. A bound function cannot be re-bound.obj.f():thisisobj, the object before the dot.- Plain
f():thisisundefinedin strict code and the global object in sloppy code.
Arrow functions have no this of their own. They use the this of the surrounding code, fixed at the place where the arrow is written, and call() or bind() cannot change it. Class bodies and modules are strict, so a detached method sees undefined.
Usage notes
- Detached methods lose
this. Passingobj.methodas a callback (setTimeout(obj.method)) removes the object. Use an arrow wrapper,bind(), or an arrow-function class field. - Use arrows for callbacks inside methods so they keep the method's
this. Do not use an arrow as an object method that needs its ownthis. - Event listeners. With
addEventListenerand a regular function,thisis the element the listener is attached to. - Prefer
constandletto avoid function-widevarsurprises, and keep scopes small. - Do not rely on the global
this. It is a sloppy-mode accident, and it differs between scripts, modules and Node.js.
Browser support
Scope rules, closures and this binding work the same in every current browser and runtime. Block-scoped declarations and arrow functions need an ES2015 engine.
Related
this, strict mode, closures, hoistingbind(),call(),apply()- Lessons: Scope and Hoisting, The
thiskeyword, Closures