(function(){
const root = this;
const generateName = (function(){
let postfix = 0;
return function(description){
postfix+=1
return `@@${description}_${postfix}`
}
})()
const SymbolPolyfill = function(description){
//判断有没有使用new操作符
if(this instanceof SymbolPolyfill) throw new TypeError("Symbol is not a constructor")
const str = description==undefined?undefined:String(description)
const symbol = Object.create( {
toString(){
return this.__Name__
},
valueOf(){
// throw new Error('Cannot convert a Symbol value')
return this
}
})
Object.defineProperties(symbol,{
"__Description__":{
value:str,
writable:false,
enumerable:false,
configurable:false
},
"__Name__":{
value:generateName(str),
writable:false,
enumerable:false,
configurable:false
}
})
return symbol
}
let forMap = {}
Object.defineProperties(SymbolPolyfill,{
"for":{
//这里传进去的是SYmbol的描述项
value:function(description){
let str = description===undefined?undefined:String(description)
return forMap[str]?forMap[str]:forMap[str] = SymbolPolyfill(str)
},
enumerable:false,
writable:true,
configurable:true
},
"keyFor":{
//这里是Symbol的声明值
value:function(symbol){
console.log(symbol)
for(let key in forMap){
console.log(key)
if(forMap[key]===symbol) return key;
}
},
enumerable:false,
writable:true,
configurable:true
}
})
root.SymbolPolyfill = SymbolPolyfill
})()
var aa = SymbolPolyfill.for('aaaaa')
var bb = SymbolPolyfill.for('bbbb')
console.log(bb.valueOf())
JS中亲手教你实现一个Symbol
最新推荐文章于 2024-04-12 06:19:16 发布