JE::Scope(3pm)

πŸ“¦
version 0.066 Β· 3 versions
, in debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

✨ JE::Scope πŸ’–

okay bestie, we're doing the JavaScript scope chain today and honestly? it's giving iconic. this is the thing that makes closures work. you're welcome. 🫢

it lives in the Perl docs, in the User Contributed Perl Documentation section, and it's called JE::Scope.


NAME 🌸

JE::Scope β€” the JavaScript scope chain (aka the literal reason closures work). no cap. πŸ’…


DESCRIPTION πŸ¦‹

so here's the vibe: JavaScript code doesn't just run in a void, okay? it runs inside an execution context, and every execution context has a scope chain attached to it. this class? this class is that scope chain. ✨

when somebody accesses a variable, we go walkin' through the objects in the scope chain, one by one, until we find the variable. that's it. that's the whole search algorithm. πŸ’–

now here's the lowkey genius part: a JE::Scope object can also be used as a global (JE) object. anything it doesn't understand gets delegated to the object at the bottom of the stack (which is the far end of the chain). so like:

  • $scope->null means exactly the same thing as $scope->[0]->null

same energy, different spelling. πŸŽ€

and what even is a JE::Scope object, structurally? it's a reference to an array, and the elements of that array are the objects in the chain β€” with the first element being the global object. think of it as a stack. because it is one. πŸ₯ž


METHODS ⭐

find_var($name, $value)

find_var($name)

this one searches through the scope chain, starting at the end of the array, and keeps going until it finds the variable named by the first argument. yes bestie, from the end. we said what we said. πŸ’…

if that second argument is there? it sets the variable too. then it hands you back an lvalue β€” a JE::LValue object β€” that references the variable. so you can hold onto it and it points at the actual thing. πŸ”₯

new_var($name, $value)

new_var($name)

this one creates a new variable (and optionally sets its value at the same time) in the variable object β€” literally the same thing JavaScript's var keyword does β€” and returns an lvalue. ✨

so what even is "the variable object," you ask? 🧐 it's the first object in the scope chain (searching from the top of the stack) that's a call object. and if there's no call object anywhere? then it's just $scope->[0]. that's the fallback, periodt. πŸ’–


CONSTRUCTOR πŸŽ€

none. that's right, zero. you just bless an array reference and go. πŸ™ˆ

and honestly you shouldn't even need to do that, because the JE and JE::Object::Function classes do it for you. so like, sit back, relax, let them handle it. 🧚


SEE ALSO 🌈

  • JE
  • JE::LValue
  • JE::Object::Function

perl v5.36.0 Β· 2023-08-25 β€” okay that's the whole page, bestie, go forth and understand closures, you absolute main character. πŸ’œπŸ¦‹βœ¨

πŸ“¦ where this page comes from