MV/MZ - ES6 and you: cool stuff you might not know you can do.
So one thing that's been made apparent to me over the last few weeks is that there are a fair few coders in the community who aren't yet aware of some of the coolest stuff ES6 gave us, so this is just a topic to bring your attention to those things and hopefully make your coding lives a bit easier.Let and Const
If you've come from MV, or are still there, you're going to be intimately familiar with var. There's barely a plugin from the earlier days that doesn't have it somewhere, and obviously it serves to create variables in code. If you need a value with a specific name that you'll use later, you declare it with var. So what are let and const?
Well, they're basically var with more structure: let defines variables that can change within the block you declared them, and const defines constant variables where the value will never change. If it changes, let. If it doesn't, const. Simple.
For example, I can do:
JavaScript:
let x = 5; x = 10; console.log(x);
// output: 10
But I can't do
JavaScript:
const x = 5; x = 10;
if I try to run this, I'll get an error because I tried to assign a value to a constant. This is handy to keep your mutable values and immutable ones safe from accidental operations; with var, there's nothing stopping you from changing a value even if it's meant to be a constant. The reasons behind no longer using var as many, and rather than try to cover them all in one topic, I'll link to a great article that explains the issues with it and why we should stop using var entirely wherever possible:
Arrow Functions
Arrow functions are basically syntactic sugar for anonymous/unnamed functions, cutting out a fair amount of bloat we no longer need to include. For example, in ES5, when passing a callback function to forEach:
JavaScript:
.forEach(function(value) { console.log(value) });
// output
1
2
3
4
5
What we can do now is take out the "function" keyword and the brackets around the parameter name, remove the "return" keyword if one was needed, and use an arrow (=>) to replace the block brackets. So it becomes:
JavaScript:
.forEach(value => console.log(value));
// output as above
Much neater! But Trihan, what if we have multiple parameters? I hear none of you ask. Well then you just put the brackets back:
JavaScript:
.reduce((accumulator, value) => accumulator + value, 0);
// output 15
Note that the return keyword isn't needed for this, where it would have been in ES5.
As pointed out by @TheoAllen, you can store arrow functions in variables like you can with others:
JavaScript:
const fn = () => console.log("stuff");
Multi-line Strings
Strings can now be declared with visible newlines by enclosing them in backticks instead of quotes. So instead of
JavaScript:
const string = "This\nspans\nmultiple\nlines";
you can do
JavaScript:
const string = `This spans multiple lines`;
Parameter Defaults
In ES5, defining default values for a parameter had to be done in-block using a logical OR. For example:
JavaScript:
var calculateArea = function(width, height) { width = width || 100; height = height || 80; return width * height; }
But now, in ES6, we can include the defaults in the parameter definition:
JavaScript:
var calculateArea = function(width = 100, height = 80) { return width * height; }
And you can even combine that with arrow functions to make it even more streamlined:
JavaScript:
const calculateArea = ((width = 100, height = 80) => width * height); calculateArea();
// output 4000
Template Literals
This is a fun one. So in ES5, when placing variables into strings, you had to terminate the string, concatenate the variable, then reopen the string to continue. Like so:
JavaScript:
var variable = 5; console.log("The variable's value is " + variable + ".");
But now, thanks to the ever-trusty backtick, that's a thing of the past because we can use template literals to put the variable right into the string without having to interrupt it!
JavaScript:
const variable = 5; console.log(`The variable's value is ${variable}.`);
Spread Operator
You can actually see this one in the base MZ code for constructors. The spread operator takes the iterable object that follows it and expands it into individual arguments; this can be used in any place where zero or more arguments or elements are expected, so you can use it in function calls or array assignment.
If you've ever looked at the MV base code, you'll have seen a lot of things like this:
JavaScript:
function ClassName() { this.initialize.apply(this, arguments); }
And if you look at MZ, you'll more than likely see this instead:
JavaScript:
function ClassName() { this.initialize(...arguments); }
These do the same thing, it's just that in ES5 we didn't have any way to extract an array into distinct values when passed to a function. To give a concrete example:
JavaScript:
const args = ["Trihan", "JavaScript", "developer"]; function myFunc(name, language, profession) { console.log(`My name is ${name} and I'm a ${language} ${profession}!`); } myFunc(...args);
Output: "My name is Trihan and I'm a JavaScript developer!"
Among its other uses, you can use this for array assignment; in fact, this is the example that prompted me to write this topic in the first place:
JavaScript:
let arr1 = ; const arr2 = ; arr1 = [...arr1, ...arr2]; console.log(arr1);
// output:
Destructuring Assignment
This feature makes it easier to extract values from arrays and properties from objects into distinct variables:
Array destructuring:
JavaScript:
const animals = ["dog", "cat"]; const = animals; console.log(ani1, ani2);
// output "dog cat"
Object destructuring:
JavaScript:
const dog = { name: "Boss", breed: "Malamute" }; const { name, breed } = dog; console.log(name, breed);
// output "Boss Malamute"
Enhanced Object Literals
In ES5, when creating an object's properties and assigning them via variable, you had to declare the property:
JavaScript:
const name = "Trihan"; const occupation = "Developer"; const age = 37; const person = { name: name, occupation: occupation, age: age };
Well now you don't have to do that!
JavaScript:
const name = "Trihan"; const occupation = "Developer"; const age = 37; const person = { name, occupation, age };
As long as the property name is going to be the same as the variable identifier, there's no need to explicitly declare it any more.
Promises
Promises are JavaScript's answer to asynchronous processing. They're a bit complex to get to grips with if you're not used to async functions but Kino has a great explanation of them here:
JavaScript Promises
JavaScript Promises Promises are the new kid on the block when it comes to handling asynchronous functions in JavaScript. But, before we can talk promises, we have to talk about asynchronous briefly. Asynchronous Functions And Callback Triangle Asynchronous functions are functions that...
forums.rpgmakerweb.com
Classes
ES6 has classes now! That's great! But there are some things to be aware of. First of all, let's look at how we used to have to create a "class" vs how we do it in ES6:
ES5:
JavaScript:
function Window_CustomFunc() { this.initialize.apply(this, arguments); }Window_CustomFunc.prototype = Object.create(Window_Base.prototype); Window_CustomFunc.prototype.constructor = Window_CustomFunc;Window_CustomFunc.prototype.initialize = function(rect) { Window_Base.prototype.initialize.call(this, rect); // other window-specific stuff };Window_CustomFunc.prototype.someFunction = function() { // more stuff };
ES6:
JavaScript:
class Window_CustomFunc extends Window_Base { constructor(rect) { super(rect); // other window-specific stuff } someFunction() { // more stuff } }
As you can see, there's a lot less involved. But it's important to remember that JavaScript still does not have classes. This is just syntactic sugar for the same code we used to use before, and under the hood JavaScript classes don't have the same sort of features and real inheritance that other languages do. It's still a lot cleaner and easier to write, though.
Modules
Not something I really use myself, but including it here for the sake of completion. Modules are represented by separate .js files, and we can use the export/import statements to either make a module object available externally, or import one from another module:
module.js
JavaScript:
export const myConst = 5; export function myFunc() { // stuff }
some_other_file.js
JavaScript:
import { myConst, myFunc } from 'module' console.log(myConst);
output: 5
And that's mostly it for the new stuff in ES6! Hopefully there was something here that you either didn't know about or didn't fully understand yet. Let me know in the comments if I've missed anything out or you have further insight on lesser-known JS features!
本贴来自国际rpgmaker官方论坛作者:Trihan处,因国际论坛即将永久关站,为了存档多年珍贵资料,署名转载到本论坛存档,由于官方帖子为英文原帖,需要中文翻译请点击论坛顶部切换语言为中文就可以将帖子翻译成中文浏览,方便大家随时查看,原文地址:https://forums.rpgmakerweb.com/threads/mv-mz-es6-and-you-cool-stuff-you-might-not-know-you-can-do.152021/
页:
[1]