Symbol

A symbol is a unique and immutable data type.The Symbol object is an implicit object wrapper for the symbol primitive data type.
@cite https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

Local Symbols vs. Global Symbols

// Create a local symbol.
var s1 = Symbol('foo');
var s2 = Symbol('foo');

s1 == s2;
// OUTPUT: false

// Create a global symbol.
var S1 = Symbol.for('foo');
var S2 = Symbol.for('foo');

S1 === S2;
// OUTPUT: true

// Retrive the description from a global symbol.
Symbol.keyFor(S1);

Object.getOwnPropertySymbols()

var sname = Symbol('name');

var person = {
    [sname]: 'Jack';
};

Object.getOwnPropertySymbols(person);
// OUTPUT: [Symbol(name)]

内置 Symbols

内置符号用于向特定运算符或控制语句提供对象的指示信息。

Symbol.hasInstance

Symbol.hasInstance 属性可以令 instanceof 运算符作用于普通的对象:

var F = {};
F[Symbol.hasInstance] = () => true;

[] instanceof F;
// OUTPUT: true

对于函数对象,Symbol.hasInstance 系内置属性,无法通过下标运算符变更,但仍可以通过 Object.defineProperty() 方法修改:

function F() {}
Object.defineProperty(F, Symbol.hasInstance, { value: () => true });

[] instanceof F;
// OUTPUT: true

Symbol.iterator

var I = {};
I[Symbol.iterator] = (function() {
    var cursor = 0;

    // The iterator SHOULD be a function.
    return function() {
        // When iterator invoked, an object containing "next()" SHOULD be returned.
        return {
            next: function() {
                // When "next()" invoked, an object with "value" and "done" SHOULD be returned.
                return {
                    value: ++cursor,
                    done: cursor > 3
                };
            }
        }
    };
})();

[...I];
// OUTPUT: [ 1, 2, 3 ]

利用生成函数,可以简洁地生成迭代器:

var myIterable = {}
myIterable[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
};
[...myIterable];
// OUTPUT: [ 1, 2, 3 ]
// @cite https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator

请阅读 Iterator 一章,了解有关迭代器的更多信息。

SEE

results matching ""

    No results matching ""