-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbol.js
68 lines (65 loc) · 1.55 KB
/
symbol.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var generateName = (function () {
var endfix = 0
return function (desc) {
endfix++
return `@@${desc}_${endfix}`
}
})()
var SymbolPolyfill = function Symbol(desc) {
if (this instanceof SymbolPolyfill) throw new TypeError('Symbom is not a function')
var descString = desc === undefined ? undefined : String(desc)
var symbol = Object.create({
toString: function () {
return this.__Name__
},
valueOf: function () {
throw new Error('Cannot convert a Symbol value')
}
})
Object.defineProperties(symbol, {
'__Description__': {
value: descString,
writable: false,
enumerable: false,
configurable: false
},
'__Name__': {
value: generateName(descString),
writable: false,
enumerable: false,
configurable: false
}
})
return symbol
}
var forMap = {}
Object.defineProperties(SymbolPolyfill, {
'for': {
value: function (desc) {
var descString = desc === undefined ? undefined : String(desc)
return forMap[descString] ? forMap[descString] : forMap[descString] = SymbolPolyfill(descString)
},
writable: true,
enumerable: false,
configurable: true
},
'keyFor': {
value: function (symbol) {
for (let key in forMap) {
if(forMap[key] === symbol) return key
}
},
writable: true,
enumerable: false,
configurable: true
}
})
var a = SymbolPolyfill('a')
var b = SymbolPolyfill('a')
console.log(a === b)
console.log(a.toString())
var obj = {}
obj[a] = '1111'
obj[b] = '222'
console.log(obj)
// console.log(a + 1)