symbol, function arrows

Symbol

Outline

  • The reason for introducing the Symbol: to ensure that the name of each property is unique, thus preventing the conflict from the fundamental attribute names.

  • Original data structure Symbol, represents a unique value.

  • Symbol by Symbol value generating function.

    let s = Symbol();
    
    typeof s
    // "symbol"
  • Note that Symbolyou can not use pre-function newcommand, otherwise it will error. This is because the Symbol are not objects, so you can not add attributes. Basically, it is a data string of similar type.

  • SymbolFunction can take a string as parameter Symbol represent a description of examples, the primary purpose of the console display, or when converted to a string, relatively easy to distinguish.

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

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

s1.toString() // "Symbol(foo)"
s2.toString() // "Symbol(bar)"

s1And s2two Symbol values. If no arguments, they are in the output console Symbol(), is not conducive to differentiate. After the parameters have, which is equivalent to adding a description, it is possible to distinguish when the output, which is a value in the end.

  • If the argument Symbol is an object, it will call the object's toStringmethod, convert it to a string, and then it generates a Symbol value.

    const obj = {
      toString() {
        return 'abc';
      }
    };
    const sym = Symbol(obj);
    sym // Symbol(abc)
  • Note that, Symbolthe parameters represent a description of the function of only the current value of the Symbol, and therefore the same parameter Symbolfunction return value is not equal.

    / 没有参数的情况
    let s1 = Symbol();
    let s2 = Symbol();
    
    s1 === s2 // false
    
    // 有参数的情况
    let s1 = Symbol('foo');
    let s2 = Symbol('foo');
    
    s1 === s2 // false

    The above code, s1and s2both Symbolreturn value of the function, and the same parameters, but they are not equal.

  • Symbol values ​​can not perform operations with other types of values, error.

    let sym = Symbol('My symbol');
    
    "your symbol is " + sym
    // TypeError: can't convert symbol to string
    `your symbol is ${sym}`
    // TypeError: can't convert symbol to string

    However, Symbol values ​​can be explicitly converted to a string.

    let sym = Symbol('My symbol');
    
    String(sym) // 'Symbol(My symbol)'
    sym.toString() // 'Symbol(My symbol)'

    In addition, Symbol values ​​can also be converted to a Boolean value, but the value can not be converted.

    let sym = Symbol();
    Boolean(sym) // true
    !sym  // false
    
    if (sym) {
      // ...
    }
    
    Number(sym) // TypeError
    sym + 2 // TypeError

Symbol.prototype.description

Symbol created, you can add a description.

const sym = Symbol('foo');

The above code, symthe character string is described foo.

However, the need to read the Symbol explicitly described to a string, i.e., the following wording.

const sym = Symbol('foo');

String(sym) // "Symbol(foo)"
sym.toString() // "Symbol(foo)"

ES2019 provides an example of property description, direct return Symbol description.

const sym = Symbol('foo');

sym.description // "foo"

As a Symbol attribute name

Since each Symbol values ​​are not equal, which means Symbol values ​​can be used as an identifier for the attribute name of the object, you can guarantee the property of the same name does not appear. This is useful for an object by a plurality of modules, one key can be prevented from being rewritten or overwritten carelessly

let mySymbol = Symbol();

// 第一种写法
let a = {};
a[mySymbol] = 'Hello!';

// 第二种写法
let a = {
  [mySymbol]: 'Hello!'
};

// 第三种写法
let a = {};
Object.defineProperty(a, mySymbol, { value: 'Hello!' });

// 以上写法都得到同样结果
a[mySymbol] // "Hello!"

The above code structure by brackets and Object.definePropertydesignated as a Symbol value, the attribute name of the object.

Note that, Symbol value as an object name attribute, not by the dot operator.

const mySymbol = Symbol();
const a = {};

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

In the above code, since the operator always points behind the string, it does not read mySymbolthe value as an identification name of the referenced, resulting in athe attribute name is actually a string instead of a Symbol value.

Similarly, within the object, when using the Symbol attribute is defined, Symbol values ​​must be placed in square brackets.

let s = Symbol();

let obj = {
  [s]: function (arg) { ... }
};

obj[s](123);

The above code, if snot in square brackets, the keys of the property is the string s, rather than srepresent a value that Symbol

Using enhanced object wording of the code above objobject can write less verbose.

let obj = {
  [s](arg) { ... }
};

Symbol types may also be used to define a set of constants to ensure that the set value of the constant are not equal.

const log = {};

log.levels = {
  DEBUG: Symbol('debug'),
  INFO: Symbol('info'),
  WARN: Symbol('warn')
};
console.log(log.levels.DEBUG, 'debug message');
console.log(log.levels.INFO, 'info message');

Here is another example.

const COLOR_RED    = Symbol();
const COLOR_GREEN  = Symbol();

function getComplement(color) {
  switch (color) {
    case COLOR_RED:
      return COLOR_GREEN;
    case COLOR_GREEN:
      return COLOR_RED;
    default:
      throw new Error('Undefined color');
    }
}

The greatest advantage of using a constant value Symbol is any other value can not have the same value, so you can ensure that the above switchstatement will work as designed.

Another point to note, Symbol attribute value as the name of the property or public property, not private property.

Example: the elimination of magic string

topic

Brief symbol

  • Symbol ES6 is a new property, represented by a given name as a unique identifier, the value of this type can be created

    let id=symbol(“id”)
  • Symbl ensure uniqueness, even with the same name, also have different values, we create a field, just know that the corresponding symbol people can access, use, useful symbol, symbol is not 100% hidden, there are built-in methods Object.getOwnPropertySymbols (obj) you can get all the symbol.

  • There is also a method Reflect.ownKeys (obj) Returns the object all keys, including the symbol.

  • So not really hidden. But most libraries built-in methods and grammatical structures they follow the common convention is hidden,

ES6 arrow characteristic function

ES6 increase the function of the arrow, the basic syntax is

let func = value => value;

Equivalent to

let func = function (value) {
    return value;
};

Arrow difference function ordinary function in that:

  • Arrow function does this, so it is necessary to determine the value of this by looking up the scope chain, which means that if the function is non-arrow arrow function included, this is the most recent layer of non-binding function of this arrow
  • Arrow function does not own arguments object, but you can access the arguments object peripheral functions
  • By not calling the new keyword, also did not new.target value and prototype

Some of the new features simply talk about ES6

  • ES6 increase the let, const variables declared in the declarations and definitions of variables, the concept of local variables,
  • There are more attractive assignment structure assignment,
  • Meanwhile ES6 for strings, arrays, regular, objects, functions, etc. to expand the number of methods, such as simple expression template string string aspects of the default parameter function aspects, aspects of the object attributes,
  • ES6 also introduces a new data type symbol, and set the new data structure map, symbol can be detected by typeof
  • To solve the problem of asynchronous callback, the introduction of promise and generator,
  • As well as the realization of the most attractive and Class module, you can better by Class of object-oriented programming, module loading easy to use modular programming, of course, take into account the browser compatibility, we need to use in the actual development babel compile

Important features:

  • ES5 only global scope and function scope, the benefits of block-level scope is a function of expression is no longer in need of immediate execution, loop closures are no longer a problem
  • rest parameters: a parameter obtaining extra function, so that no arguments object, and
  • promise: an asynchronous programming solution that is more reasonable than traditional solutions callback functions and events formidable
  • Modular: its main function modules constituting two commands, export and import, export predetermined command to the external interface module, import function for inputting a command provided by other modules

Arrow What is the difference function and function

Arrow function simply do not own this binding, when you call this function in the arrow, just simply looking up the scope chain, find the nearest one used to use this

Guess you like

Origin www.cnblogs.com/zhoujingguoguo/p/11539609.html