Anywhere you can use a string or number property, you can use a symbol.
This includes object literal properties and Object.defineProperty()
and Object.defineProperties()
.
An object literal can only use a symbol as a property inside the computed property syntax.
let s1 = Symbol('foo'), s2 = Symbol('bar'), s3 = Symbol('baz'), s4 = Symbol('qux'); //from www . java 2s. c om let o = { [s1]: 'foo val' }; // Also valid: o[s1] = 'foo val'; console.log(o); // {Symbol{foo}: foo val} Object.defineProperty(o, s2, {value: 'bar val'}); console.log(o); // {Symbol{foo}: foo val, Symbol(bar): bar val} Object.defineProperties(o, { [s3]: {value: 'baz val'}, [s4]: {value: 'qux val'} }); console.log(o);
Object.getOwnPropertyNames()
returns an array of regular properties on an object instance.
Object.getOwnPropertySymbols()
returns an array of symbol properties on an object instance.
The return values of these two methods are mutually exclusive.
Object.getOwnPropertyDescriptors()
will return an object containing both regular and symbol property descriptors.
Reflect.ownKeys()
will return both types of keys:
let s1 = Symbol('foo'), s2 = Symbol('bar'); /*from ww w . j a v a 2s .co m*/ let o = { [s1]: 'foo val', [s2]: 'bar val', baz: 'baz val', qux: 'qux val' }; console.log(Object.getOwnPropertySymbols(o)); // [Symbol(foo), Symbol(bar)] console.log(Object.getOwnPropertyNames(o)); // ["baz", "qux"] console.log(Object.getOwnPropertyDescriptors(o)); // {baz: {...}, qux: {...}, Symbol(foo): {...}, Symbol(bar): {...}} console.log(Reflect.ownKeys(o)); // ["baz", "qux", Symbol(foo), Symbol(bar)]