Add to the Scoping blog post.

This commit is contained in:
Dave Smith-Hayes 2024-11-18 21:49:38 -05:00
parent 6e5a955043
commit 02c7cfc0c3

View File

@ -27,7 +27,7 @@ callbacks to events that will be run when that particular event is emitted.
import EventEmitter from "node:events"; import EventEmitter from "node:events";
const em = new EventEmitter(); const em = new EventEmitter();
em.on("home-event", function () { em.on("some-event", function () {
console.log("Something happened."); console.log("Something happened.");
}); });
@ -65,6 +65,14 @@ class SomePool extends EventEmitter {
public getFreeConnectionCount(): number { public getFreeConnectionCount(): number {
return this.freeConnections; return this.freeConnections;
} }
public function getConnection() {
this.emit("pre-connect");
if (this.freeConnections) {
// get a connection
}
}
} }
``` ```
@ -72,5 +80,37 @@ So now, in any callback function* we can get the total number of free
connections in the `SomePool` class. connections in the `SomePool` class.
```typescript ```typescript
title= const pool = new SomePool();
pool.on("pre-connect", function () {
if (this.freeConnections) {
this.freeConnection = this.freeConnection - 1;
}
});
``` ```
This is a really impractical use of `EventEmitter`, but I think it does a good
job at illustrating the scope of the callback function on the `on` method and
how it can alter the state of the `SomePool` class. There is definitely a case
for when this can be super helpful and useful.
## The Arrow Function
One of the big things in JavaScript is to use this nifty little short-hand to
create a function:
```typescript
[1, 2, 3].map((i) => i + 1);
```
This is super useful to keeping code clean and concise - but there is a huge
caveat using the arrow function over the classic function definition. When you
do an arrow function, you are not inheriting the scope of the object you are
attaching the callback to.
So in the example above, the object is the Array object, implicitly
instantiated, and having its method `map` called (which iterates over each of
the items in an Array, and does something, in this case, adding 1 to it).