From 03f03ff47157093e9ea1289ced147587196c18b3 Mon Sep 17 00:00:00 2001 From: Dave Smith-Hayes Date: Wed, 9 Oct 2024 21:17:08 -0400 Subject: [PATCH] Add a blog post about JS scope. --- posts/scope-with-javascript.md | 76 ++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 posts/scope-with-javascript.md diff --git a/posts/scope-with-javascript.md b/posts/scope-with-javascript.md new file mode 100644 index 0000000..faf7bb9 --- /dev/null +++ b/posts/scope-with-javascript.md @@ -0,0 +1,76 @@ +--- +title: JavaScript Scoping +description: A blog post talking about how JavaScript handles scoping +date: 2024-08-11 +tags: + - development + - javascript + - typescript +slug: javascript-scoping +draft: true +--- + +## The EventEmitter Class + +The other day I was reading through the Types file of the MariaDB JavaScript +library (since its the better MySQL library for Node.js), and I noticed that +the `PoolConnection` class _actually_ extends the `EventEmitter` class from +Node.js. That in and of itself isn't that exciting, but it had me thinking +about the utility of extending that particular class, and how the scopeing of +the code used in that class would actually work. + +I never put a lot of thought into it, but if you have used the `EventEmitter` +class in JavaScript at any point in your life, you know that you can attach +callbacks to events that will be run when that particular event is emitted. + +```javascript +import EventEmitter from "node:events"; + +const em = new EventEmitter(); +em.on("home-event", function () { + console.log("Something happened."); +}); + +em.emit("some-event"); +``` + +When you call `em.emit("some-event")` anywhere this `EventEmitter` exists in +code, you will get a console log from inside that function. Okay, makes sense, +so what's interesting about this? + +Well the scope of the callback function actually ineherits the called method's +properties and methods. This can get really interesting if you are extending +the functionality of the `EventEmitter` class - like in the MariaDB module's +`PoolConnection` class. + +## Getting In-Depth with Scope + +So say we had a class that extends the `EventEmitter` class and had some +methods with some state we cared about in the callback. In the MariaDB context +that could be anything that has to do with the connection pool - like maybe +how many open connections are available. We can sketch this out in a very +trivial class example in TypeScript. + +```typescript +import EventEmitter from "node:events"; + +class SomePool extends EventEmitter { + private freeConnections: number; + + public constructor() { + super(); + this.freeConnections = 4; + } + + public getFreeConnectionCount(): number { + return this.freeConnections; + } +} +``` + +So now, in any callback function* we can get the total number of free +connections in the `SomePool` class. + +```typescript +title= +```