ES6 articles (11) - Symbol


(1) Overview:
for ES6 introduce a new primitive data type Symbol, represents a unique value.
Note: It is the seventh JavaScript language data types, the first six are: undefined, null, Boolean (Boolean)
String (String), value (Number The), the object (Object).

ES6 introduced its purpose is to solve the problem object property name conflicts, the object attribute names are strings of ES5, attribute names likely to cause
conflict. Property name of the object can now have two types (the original strings and new Symbol type)

Usage: Symbol value generated by Symbol function, be careful not to use the new command before the Symbol function, otherwise it will error
(Symbol This is because the value of the original type, not an object, and therefore can not add value Symbol object, which is similar to a string other types)

Examples:
the let S = the Symbol ();

typeof s
// "symbol"

let s1 = Symbol('foo');
let s2 = Symbol('bar');

s1 // Symbol(foo)
s2 // Symbol(bar)

s1.toString () // "Symbol (foo)"
s2.toString () // "Symbol (bar)"
the Sym function can take a string as parameter Symbol showing an example of representation, is output in order to distinguish them.
Note: 1. If the parameter Symbol is an object, it will first call the toString method of that object, convert it to a string
, and then it generates a Symbol value.
2.Symbol parameters represent a description of a function of only the current value of the Symbol, and therefore the same parameter Symbol function return value is not equal.
3.Symbol value can not be calculated with the values of other types of error.
4.Symbol value may be explicitly converted string, boolean, but not converted value.

(2) Symbol.prototype.description returned Symbol description (ES2019 incorporated)

const sym = Symbol ( 'foo' );
before acquiring described, need to explicitly into a string
String (sym) // "the Symbol (foo)"
sym.toString () // "the Symbol (foo)"

So now you can get
sym.description // "foo"

(3) as a Symbol attribute name
Symbol value as the property name, to ensure that the properties of the same name does not appear, we can square brackets with the results and Object.defineProperty
will specify the property name as a Symbol value.
Examples:
the let mySymbol the Symbol = ();

// first writing
the let A = {};
A [mySymbol] = 'the Hello!';

// second writing
the let A = {
  [mySymbol]: '! The Hello'
};

// third writing
the let A = {};
Object.defineProperty (A, mySymbol, {value: 'the Hello!'});

// get the same results are written above
a [mySymbol] // "Hello! "

Note:
1.Symbol name as an attribute value, can not use the dot operator, the operator will be used as a dot string (attribute name as a string)

Examples:
const = mySymbol the Symbol ();
const A = {};

a.mySymbol = 'Hello!';
a[mySymbol] // undefined
a['mySymbol'] // "Hello!"

Another example:
the let S = the Symbol ();

{obj = the let
  [S]: function (Arg) {...}
// S in square brackets
};
obj [S] (123);

2.Symbol type may be used to define a set of constants, the set value of the constant to ensure unequal
3.Symbol name as the attribute value, the attribute is public property, is not private property

(4) Example: Elimination Magic string
magic string means: code appears more than once in the form of a specific string or numeric codes and strong coupling.
For example:
function the getArea (Shape, Options) {
  the let Area = 0;

  switch (shape) {
    case 'Triangle': // 魔术字符串
      area = .5 * options.width * options.height;
      break;
    /* ... more code ... */
  }

  return area;
}

getArea ( 'Triangle', {width: 100, height: 100}); // magic string

Symbol eliminate the use of the magic string
const = {shapeType
  Triangle: Symbol ()
};

function getArea(shape, options) {
  let area = 0;
  switch (shape) {
    case shapeType.triangle:
      area = .5 * options.width * options.height;
      break;
  }
  return area;
}

getArea(shapeType.triangle, { width: 100, height: 100 });


Traversal (5) attribute name
Object.getOwnPropertySymbols method, you can get all of the specified object Symbol attribute names.
[Note: This property does not appear in the for ... in, for ... of the cycle, it will not Object.keys (), Object.getOwnPropertyNames (),returns]

Object.getOwnPropertySymbols method returns an array members are all Symbol value as the attribute name of the current object.
obj = {} const;
the let A = the Symbol ( 'A');
the let B = the Symbol ( 'B');

obj[a] = 'Hello';
obj[b] = 'World';

const objectSymbols = Object.getOwnPropertySymbols(obj);

objectSymbols
// [Symbol(a), Symbol(b)]

Another new API, Reflect.ownKeys method can return the keys of all types, including conventional keys and Symbol keys.

let obj = {
  [Symbol('my_key')]: 1,
  enum: 2,
  nonEnum: 3
};

Reflect.ownKeys(obj)
//  ["enum", "nonEnum", Symbol(my_key)]

(6)Symbol.for(),Symbol.keyFor() 

Symbol.for (): Sometimes, we want to re-use the same Symbol value, Symbol.for ways to do this. It accepts a string argument, then there is no search parameter to the value of the name as a Symbol. If so, this Symbol return value,
otherwise a new and returns a string with the name of Symbol value.

Symbol.keyFor method returns the value of a key Symbol type registered.
Note:. 1 Symbol.for () and Symbol () Both versions will generate a new Symbol. The difference between them is that the former will be registered in a search for the global environment, which is not
an example: the let Symbol.for S1 = ( "foo");
Symbol.keyFor (S1) // "foo"

Symbol s2 = the let ( "foo");
Symbol.keyFor (s2) // undefined
code above, the variables belonging Symbol s2 value is not registered is returned undefined

Symbol 2.Symbol.for value is registered name, is the global environment, can take the same value or different service worker in the iframe.

(7) Example: Singleton mode module
Singleton pattern: calling a class, are the same at any time to return to one example.
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];
keys generated using the Symbol method, external reference value can not, can not and will not rewrite covered
but there are problems
is, if the implementation of the script several times, each time resulting FOO_KEY is not the same. Although Node script execution will result cache, under normal circumstances, would not execute the same script several times,
but the user can manually clear the cache, it is not absolutely reliable.

(8) the value of the built-Symbol
ES6 provides 11 values Symbol built, the language used in the method inwardly directed
a.Symbol.hasInstance
Symbol.hasInstance properties of the object, point to an internal method. When using other objects instanceof operator, it determines whether the instance of that object, This method is called.

b.Symbol.isConcatSpreadable
Symbol.isConcatSpreadable property of an object is equal to a Boolean value that indicates when the object is used Array.prototype.concat (), whether to expand.

c.Symbol.species
Symbol.species property of an object, a point constructor. When you create a derived object, the use of the property.
Its main purpose is that some libraries are modified on the basis of the base class, then use inheritance when the subclass method, the authors might want to return an instance of the base class instead of an instance of a subclass.

d.Symbol.match
Symbol.match property of an object, refers to a function. When performing str.match (myObject), if this attribute is present, it calls, the method returns the return value.

e.Symbol.replace 
Symbol.replace property of an object, a pointing method, the object is invoked when String.prototype.replace method will return a return value of the method.

f.Symbol.search
object Symbol.search property, a pointing method, the object is invoked when String.prototype.search method will return a return value of the method.

g.Symbol.split
Symbol.split property of an object, a pointing method, the object is invoked when String.prototype.split method will return a return value of the method.

h.Symbol.iterator 
Symbol.iterator properties of the object point to the default method is to traverse the object.

i.Symbol.toPrimitive
Symbol.toPrimitive property of an object, a point method. When the object is converted to values of the original type, this method will call, it returns the original value of the corresponding object type.

j.Symbol.toStringTag 
Symbol.toStringTag property of an object, a point method. When calling the object method Object.prototype.toString above, if the attribute exists, its return value will appear in the toString method returns a string representing the type of object. That is, this attribute can be used to customize the [object Object] or [the Array object] that the string behind the object.

k.Symbol.unscopables
Symbol.unscopables properties of the object point to an object. The object specifies when used with keywords, which properties are excluded with the environment.
Ruan Yifeng ES6 Symbol objects

Guess you like

Origin blog.csdn.net/u012149906/article/details/93176612