this post was submitted on 15 Jun 2023
9 points (100.0% liked)
Programming
13387 readers
13 users here now
All things programming and coding related. Subcommunity of Technology.
This community's icon was made by Aaron Schneider, under the CC-BY-NC-SA 4.0 license.
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
These are similar but distinct concepts. Most languages have a concept of (lexical) scope, which is how variables are resolved to their values. For instance,
Here,
a
is in the global scope and it's referenced by the closurefoo
. Any changes made toa
(so long as it isn't shadowed) will also appear in thea
that can be seen insidefoo
.JS is also what's called a prototype-based language, so it has an additional more exotic concept called the "prototype chain". This is how it implements something approximating OOP inheritance - essentially, if I request
obj.x
, JS will first check ifobj
has thex
property, and if it doesn't find it, it follows the__proto__
(note: nonstandard) value to get the prototype of that object and checks there. If that prototype doesn't havex
, the process continues until it reaches the end of the chain.The JS global object (also called
window
in the browser - which has a reference to itself calledwindow
) is part of lexical scoping, but not the prototype chain. The global object is the end of the scope chain, but the end of the prototype chain isObject.getPrototypeOf(Object.prototype) == null
(note: we need to get the prototype ofObject.prototype
becauseObject
is the constructor function, not the prototype)Window
is the constructor of thewindow
object,Object.getPrototypeOf(window) == Window.prototype
andwindow.constructor == Window
. It's a weird quirk of Javascript, "classes" are actually the constructor, and when we prototype a new object it prototypes that function'sprototype
property.Thank you so much! Now it's definetely clearer