Symbol is JavaScript’s seventh (new) data type and is only an attribute of a name that is not iterated by regular methods, so you can define methods for objects that are not private but that you want to use only internally.
let s = symbol()/symbol('foo');
Copy the code
- When we define symbol, the string in parentheses is a description of the current variable.
usage
let a = {
[mySymbol]: 'hello'} orvar a = {};
a[mySymbol] = 'Hello! '; But you can't write a['mySymbol'] = 'hello'; // Is not a symbol variableThe equivalent oflet a = {
mySymbol: 'hello' // Familiarity sets in
}
Copy the code
- A [‘mySymbol’]= A.mySymbol does not equal a[mySymbol].
Where is a good place to use it?
Symbol can change strong coupling into weak coupling, which is easy to modify and maintain.
/ / strong coupling
function getArea(shape, options) {
var area = 0;
switch (shape) {
case 'Triangle': // Magic string
area = . 5 * options.width * options.height;
break;
/ *... more code ... * /
}
return area;
}
/ / weak coupling
var shapeType = {
triangle: 'Triangle'
};
function getArea2(shape, options) {
var area = 0;
switch (shape) {
case shapeType.triangle:
area = . 5 * options.width * options.height;
break;
}
return area;
}
getArea('Triangle', { width: 100.height: 100 });
getArea2(shapeType.triangle, { width: 100.height: 100 });
Copy the code
You can use symbol.for() and symbol.keyfor () in your project
// mod.js
const FOO_KEY = Symbol.for('foo');
function A() {
this.foo = 'hello';
}
if(! global[FOO_KEY]) { global[FOO_KEY] =new A();
}
module.exports = global[FOO_KEY]; In the code above, we can ensure that global[FOO_KEY] is not inadvertently overwritten, but it can still be overwritten.var a = require('./mod.js');
global[Symbol.for('foo')] = 123;
Copy the code
I think these are the symbols I will use. Make a note for yourself so you can review it next time.