javascript 的 symbol

又学到了奇怪的知识。对 sequelize 的那个[Op.eq]之类的写法很好奇,比如:

{
   [Op.between]:[1,2]
}

看了下源代码,between 这个就是个 Symbol.for(“between”),这个 symbol 我从来没用过,就研究了下。

const test = Symbol.for("test");
let obj = {
    [test]: "for test"
};
console.log("obj==", obj); //{ [Symbol(test)]: 'for test' }
console.log(JSON.stringify(obj)); // {}
obj[test] = "replace test"; 
console.log(obj); //{ [Symbol(test)]: 'replace test' }
obj[Symbol("test")] = "aaabbb";
console.log(obj); //{ [Symbol(test)]: 'replace test', [Symbol(test)]: 'aaabbb' }
console.log(obj[test]); //replace tes
console.log(obj[Object(test)]); //replace tes
let symbols = Object.getOwnPropertySymbols(obj);
for(let i in symbols) {
    console.log(symbols[i],'=', obj[symbols[i]]); //Symbol(test) = replace test; Symbol(test) = aaabbb
}
发布日期:
分类:技术

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据