This content originally appeared on DEV Community and was authored by Siddharth
If you search Google for "text adventure" and open the Developer tools, you get a neat little text adventure game to play, which involves the blue G
finding his friends red o
, yellow o
, blue g
, green l
, and the always quirky red e
.
I started wondering how they did this: They implemented a whole command system without using any external stuff, with only plain JavaScript. And so at once I started digging through the code, immediately stopped because it was obfuscated, and started thinking. The result was this simple trivia quiz (hosted here).
I'm really bad at trivia.Wondering how I'm styling those logs? Check out this explainer I wroteHow does this even work?
yes
, no
, north
, moon
, they all don't seem to be anything. If you open the DevTools and run them, you'll just get a Uncaught ReferenceError: yes is not defined
. But that gives us a hint – why don't we define it?
const yes = "yes";
// Later...
yes
// => "yes"
That works perfectly, but we have no way of saying whether it was called. But then, we can use getters.
Quick demo of getters
const obj = {
foo: 'bar',
get foo() {
return 'something entirely different'
}
}
obj.foo //=> 'something entirely different'
We obviously can't use getters on global variables, but we can just set the variables on window and add getters to them:
Object.defineProperty(window, "yes", {get: () => {
// Do something
console.log("Got yes");
return "yes";
}});
yes
// => "yes"
// => "Got yes" (logged to console)
And that's basically it, you can just keep setting variables statically or dynamically, and you basically get a command system!
What are the uses of this? I dunno, all this can be done by using regular functions instead of this. Maybe easter eggs? Maybe for some debugging?
I can't wait to see people writing code like this:
Object.defineProperty(window, "main", {get: () => {...}})
main;
// Wait, is main supposed to be a function or something?
// Linters are gonna be angry...
This content originally appeared on DEV Community and was authored by Siddharth
Siddharth | Sciencx (2021-07-30T04:33:48+00:00) Writing a command system in JavaScript. Retrieved from https://www.scien.cx/2021/07/30/writing-a-command-system-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.