Pre-release
AdventureJS Docs Downloads
Score: 0 Moves: 0
Tutorial explaining how to work with arrow functions in AdventureJS. tutorial, scope, arrow function

Advanced Scripting:Arrow Functions

Arrow functions are a compact alternative to traditional functions that was introduced to Javascript ES6 in 2016. In short, it's this: () => {} vs this: function(){}. These docs are not trying to be a Javascript manual, and you can learn more about arrow functions at MDN.

The reason we draw attention to arrow functions here is for the advanced developer who may already be familiar with them and wish to use them in contexts that pass through game.getStringArrayFunction(). The MDN recommends that arrow functions should not be used as methods, though in fact it is technically possible, but with major caveats around scope.

In instances of function(){}, the this accessor returns the game asset being operated on. In the following example, we use a function(){} call at asset.dov.examine.on_success to change the color of the rainbow gem every time it is examined. We use another function call at asset.descriptions.look to include the new color in the description.

MyGame.createAsset({
  class: "Thing",
  name: "rainbow gem",
  place: { in: "Crystalline Cavern" },
  colors: ["red", "orange", "yellow", "green", "blue", "indigo", "violet"],
  color: "red",
  descriptions: { 
    look: function () {
      return `The gem glows with a rich, glossy ${this.color}. `;
    },
  },
  dov: {
    examine: {
      on_success: function () {
        const random_color = this.colors[Math.floor(Math.random() * this.colors.length)];
        this.color = random_color;
      },
    },
  },  
});

The next example uses ()=> arrow functions in place of traditional function calls. In an arrow function, the this accessor returns a reference to window, aka the browser window, which is the top level Javascript object. Since the arrow functions aren't scoped to their game asset and haven't got any reference back to it, they need to be altered to use different methods. In the following example, we've moved the random color logic into the examine method, and saved the result as a game variable, which we can use in a placeholder.

MyGame.createAsset({
  class: "Thing",
  name: "rainbow gem",
  place: { in: "Crystalline Cavern" },
  descriptions: { 
    look: ()=> `The gem glows with a rich, glossy {gem_color}. `,
  },
  dov: {
    examine: {
      on_success: () => {
        const colors = [
          "red",
          "orange",
          "yellow",
          "green",
          "blue",
          "indigo",
          "violet",
        ];
        const random_color = colors[Math.floor(Math.random() * colors.length)];
        MyGame.setVar("gem_color", random_color);
      },      
    },
  },  
});

Further reference

tl;dr be careful when using ()=>.

You can learn more about arrow functions and scope at MDN