ES 6個人メモ——Symbol
20605 ワード
ES5 ,
, ,
Cmixin 〉,
。
ES6 Symbol,
1.Number
2.String
3.Undefined
4.Null
5.Boolean
6.Object
Symbol Symbol ,
Symbol , ,
let s1 = Symbol();
console.log(typeof s1);
PS:Symbol new ,
Symbol ,
Symbol ,
,
// Symbol ,
let s2 = Symbol('foo');
let s3 = Symbol('bar');
console.log(s2,s3);
// eg1
let mySymbol = Symbol();
let mySymbol2 = Symbol();
let mySymbol3 = Symbol();
//
let a = {
};
a = {
[mySymbol2] : 'world'
}
//
a[mySymbol] = 'hello';
//
Object.defineProperty(a,mySymbol3,{
value : 'wjy'});
console.log(a)
Symbolタイプは変数のセットを定義するためにも使用できます.この変数の値が等しくないことを保証します./*
log.levels = {
DEBUG : Symbol('debug'),
INFO : Symbol('info'),
WARN : Symbol('warn')
};
log(log.levels.DEBUG,'debug message');
*/
// :
function getArea(shape,options){
let area = 0;
switch(shape){
case 'Triangle': //
area = .5 * options.width * options.height;
break;
default:
area = "false";
break;
}
return area;
}
強結合console.log(getArea('Triangle',{
width : 100,height : 200}));
// change
function getAreaChange(shape,options){
let area = 0;
let {
PI } = Math;
switch(shape){
case shapeType.triangle:
area = .5 * options.width * options.height;
break;
case shapeType.circle:
area = PI * options.radius ** 2;
break;
default:
area = "false";
break;
}
return area;
}
let shapeType = {
// triangle : 'Triangle'
/*
,shapeType.triangle
shapeType
*/
triangle : Symbol(),
circle : Symbol()
};
console.log(getAreaChange(shapeType.triangle,{
width : 200, height : 3}));
console.log(getAreaChange(shapeType.circle,{
radius : 2 }));
属性名の巡回let {
getOwnPropertyNames , getOwnPropertySymbols , defineProperty } = Object;
let objectSymbols1 = getOwnPropertySymbols(a);
console.log(objectSymbols1)
// another example
let obj3 = {
};
let foo3 = Symbol("foo");
defineProperty(obj3,foo3,{
value : "foobar",
});
for(let i in obj3){
console.log(i); //
}
getOwnPropertyNames Symbol
getOwnPropertySymbols
console.log(getOwnPropertyNames(obj3));
console.log(getOwnPropertySymbols(obj3));
Reflect.ownKeys()
Symbol
const {
ownKeys } = Reflect;
let obj4 = {
[Symbol('my_key')]: 1,
enum : 2,
nonEnum : 3
};
console.log(ownKeys(obj4));
Symbol 。
。
let size = Symbol('size');
class Collection{
constructor(){
this[size] = 0;
}
add(item){
this[this[size]] = item;
this[size]++;
}
static sizeOf(instance){
return instance[size];
}
}
let x = new Collection();
console.log(Collection.sizeOf(x));
x.add('foo');
console.log(Collection.sizeOf(x))
const {
keys , getOwnPropertySymbols , getOwnPropertyNames } = Object;
console.log(keys(x),getOwnPropertyNames(x),getOwnPropertySymbols(x));