Page 181 - JavaScript
P. 181
}
// you can also use any javascript expression
// this one is just a string, and could also be defined with simply add()
["add"](a, b) {
return a + b;
}
// this one is dynamically evaluated
[1 + 2]() {
return "three";
}
}
let MazdaMPV = new Car("Mazda", "MPV");
MazdaMPV.add(4, 5); // 9
MazdaMPV[3](); // "three"
MazdaMPV[METADATA](); // { make: "Mazda", model: "MPV" }
Methods
Methods can be defined in classes to perform a function and optionally return a result.
They can receive arguments from the caller.
class Something {
constructor(data) {
this.data = data
}
doSomething(text) {
return {
data: this.data,
text
}
}
}
var s = new Something({})
s.doSomething("hi") // returns: { data: {}, text: "hi" }
Managing Private Data with Classes
One of the most common obstacles using classes is finding the proper approach to handle private
states. There are 4 common solutions for handling private states:
Using Symbols
Symbols are new primitive type introduced on in ES2015, as defined at MDN
A symbol is a unique and immutable data type that may be used as an identifier for
object properties.
When using symbol as a property key, it is not enumerable.
https://riptutorial.com/ 138

