0. 背景
Symbols这一节其实应该放到2016讲,但是Babel官网还是介绍了,那我们也介绍一下。
基本类型(基本数值、基本数据类型)是一种既非对象也无方法的数据。在 JavaScript
中,共有7种基本类型:string,number,bigint,boolean,null,undefined,symbol (ECMAScript 2016新增)
。
1. 概览
话不多说,先上应用代码:
(function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {
... this[key] ...
}
};
// Limited support from Babel, full support requires native implementation.
typeof key === "symbol"
})();
var c = new MyClass("hello")
c["key"] === undefined
你也许会有疑问:
2.简单介绍一下子
MDN上有这么一句话:
Symbol can have an optional description, but for debugging purposes only.
也就是说,你可以用它来调试!
// Here are two symbols with the same description:
let Sym1 = Symbol("Sym")
let Sym2 = Symbol("Sym")
console.log(Sym1 === Sym2) // returns "false"
// Symbols are guaranteed to be unique.
// Even if we create many symbols with the same description,
// they are different values.
但是你千万别以为它是个字符串,他就是个symbol
,比如下面的情况就是常见应用错误:
let Sym = Symbol("Sym")
alert(Sym) // TypeError: Cannot convert a Symbol value to a string
如果你想打印,可以这样:
let Sym = Symbol("Sym")
alert(Sym.toString()) // Symbol(Sym), now it works