ES6 new Features: Add new type: Symbol

Source: Internet
Author: User

This article all the demo running environment is Nodejs, reference: let Nodejs support ES6 lexical----Babel installation and use ;

  ES6 Adds a new data type:symbol,symbol is the perfect choice for defining the unique property name of an object;

How symbol is used

How symbol is used, symbol is not a constructor oh, if you use new symbol, you will get an error:

var sym1 = Symbol (); var sym2 = Symbol ("foo"); var sym3 = symbol ("foo"// output symbol () symbol (foo) Symbol (foo)

Even oneself is not equal to oneself :

// It is not equal to create two times with the same parameters: Symbol ("foo") = = = Symbol ("foo"//output: false

Symbol as the attribute name; Use the symbol to add a unique attribute to the object, but symbol cannot be defined as a function, only as a property;

Let obj == symbol ("hehe"= symbol ("meme"  1; Console.log (Obj[sattr1]); // this way, the value of symbol is defined as a function, and an exception occurs. OBJ[SATTR0] = () = {    return + +obj[sattr0] ;;};

We can use TypeOf to judge a variable type as the symbol type:

typeof ' symbol '//output: True typeof Symbol ('foo''symbol'//output: Truetypeof'  symbol'//output: True

If we don't know what the symbol's instance name is, how do we get to the symbol value, the symbol cannot be the for in, the For loop, and the Object.keys, object.values cannot traverse the attributes of the Symbol , and the Object gives us a getownpropertysymbols;

Let sym0 = Symbol ("o_o? ") "  = {    "heheda"}for(let prop of Object.  Getownpropertysymbols(obj)) {    //prop is the name of the symbol    / / Output: Heheda};

Or the reflection provided by ES6 : reflect.ownkeys, reflex?

Let sym0 = Symbol ("o_o? ") "  = {    "heheda"//output:[Symbol (o_o?)]
Symbol.for and Symbol.keyfor

The only difference between symbol.for and Symbol is that the two instances created by symbol.for may be equal, generating an instance based on the Symbol's parameters, and returning the same instance if the parameters are the same;

let foo = Symbol.  for " 1111 "  = Symbol.  for ("1111"= = = bar);  // Output: True // only objects created by Symbol.for can be used keyfor to find the original parameters;console.log (Symbol.keyfor (foo))//output: 1111

  

The attributes of the symbol and the use of these attributes:

  Symbol.prototype: The symbol has a pointing prototype:

// prototype for output symbol

  symbol.length: The length of the symbol is 1, which means that the call to symbol requires a parameter, of course, no arguments.

  symbol.iterator: The Symbol.iterator property of the object that points to the default walker for this object:

var myiterable == function* () {    yield1;     yield 2 ;     yield 3  //  [1, 2, 3]

  symbol.match: ES6 string to match the Symbol.match method of the object, the matching result is fully controllable, the following demo, equivalent to the string "strstring" as obj[ Symbol.match] method, and then return the user-defined value:

Let obj = {    [Symbol.match] (string){        Console.log (string);         return " Heheda " ;    }};; Console.log ("strstring". Match (obj));

  Symbol.replace: As with the above:

Let obj = {    [symbol.replace] (string){        Console.log (string);         return " replllll " ;     " sssss " // output:  sssss    replllll

  symbol.split: the same as the above.

  symbol.toprimitive: The symbol.toprimitive of the object points to a method that calls this method when the object is converted to the original, and an object is converted to the original value by three cases: String, number, default:

    varObj1 = {}; Console.log (+OBJ1);//NaNConsole.log (' ${obj1} ');//"[Object Object]"Console.log (Obj1 +"");//"[Object Object]"//Obj2 has a defined symbol.toprimitive attribute;    varObj2 ={[symbol.toprimitive] (hint) {if(Hint = =" Number") {            return Ten; }        if(Hint = ="string") {            return "Hello"; }        return true;    }    }; Console.log (+OBJ2);//10--Convert to "number"Console.log (' ${obj2} ');//"Hello"--translates to "string"Console.log (Obj2 +"");//"true"--translates to "default"}

  Symbol.tostringtag: Symbol.tostringtag, this thing is powerful, even the object's toString method has been changed, and with Object.prototype.toString.call This object output is the same, This sentiment why, after the judgment element type must use other method, the change is big ....:

Console.log ({[Symbol.tostringtag]:"Str"}.tostring ());//output: [Object str]Console.log (Object.prototype.toString.call ({[Symbol.tostringtag]:"Str"}))//output: [Object str]classCollection {Get[Symbol.tostringtag] () {return 'XXX'; } }varx =NewCollection (); Console.log (x.tostring ())//output: "[Object XXX]"
Reference:

Mdn:https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/symbol

Nanyi ECMAScript 6 Getting Started: http://es6.ruanyifeng.com/#docs/symbol

NONO
Source: http://www.cnblogs.com/diligenceday/
QQ: 287101329
: 18101055830

ES6 new Features: Add new type: Symbol

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.