当前位置:网站首页>LayaBox---TypeScript---Symbols
LayaBox---TypeScript---Symbols
2022-08-02 10:01:00 【格拉格拉】
目录
1.介绍
自ECMAScript 2015起,symbol
成为了一种新的原生类型,就像number
和string
一样。
symbol
类型的值是通过Symbol
构造函数创建的。
let sym1 = Symbol();
let sym2 = Symbol("key"); // 可选的字符串key
Symbols是不可改变且唯一的。
let sym2 = Symbol("key");
let sym3 = Symbol("key");
sym2 === sym3; // false, symbols是唯一的
像字符串一样,symbols也可以被用做对象属性的键。
let sym = Symbol();
let obj = {
[sym]: "value"
};
console.log(obj[sym]); // "value"
Symbols也可以与计算出的属性名声明相结合来声明对象的属性和类成员。
const getClassNameSymbol = Symbol();
class C {
[getClassNameSymbol](){
return "C";
}
}
let c = new C();
let className = c[getClassNameSymbol](); // "C"
2.众所周知的Symbols
Symbol.hasInstance方法,会被instanceof运算符调用。 构造器对象用来识别一个对象是否是其实例。
Symbol.isConcatSpreadable布尔值,表示当在一个对象上调用Array.prototype.concat时,这个对象的数组元素是否可展开。
Symbol.iterator方法,被for-of语句调用。返回对象的默认迭代器。
Symbol.match方法,被String.prototype.match调用。正则表达式用来匹配字符串。
Symbol.replace方法,被String.prototype.replace调用,正则表达式用来替换字符串中匹配的子串
Symbol.search方法,被String.prototype.search调用,正则表达式返回被匹配部分在字符串中的索引。
Symbol.species函数值,为一个构造函数。用来创建派生对象。
Symbol.split方法,被String.prototype.split调用。正则表达式用来分割字符串。
Symbol.toPrimitive方法,被ToPrimitive抽象操作调用,把对象转换为相应的原始值。
Symbol.toStringTag方法,被内置方法Object.prototype.toString调用。返回创建对象时默认的字符串描述。
Symbol.unscopables对象,它自己拥有的属性会被with作用域排除在外。
边栏推荐
猜你喜欢
Long battery life or safer?Seal and dark blue SL03 comparison shopping guide
迭代器失效问题
Verilog的随机数系统任务----$random
Naive Bayesian Method of Li Hang's "Statistical Learning Methods" Notes
全新荣威RX5,27寸大屏吸引人,安全、舒适一个不落
The heavyweights are coming!Spoilers for the highlights of the Alibaba Cloud Life Science and Intelligent Computing Summit
在全志V853开发板试编译QT测试
如何选择一块真正“好用的、性能高”的远程控制软件
基于列表的排队与叫号系统
Linux系统卸载,安装,升级,迁移clickHouse数据库
随机推荐
MSYS2 QtCreator Clangd 代码分析找不到 mm_malloc.h的问题补救
WPF 截图控件之文字(七)「仿微信」
一款优秀的中文识别库——ocr
Pytorch的LSTM参数解释
二维数组零碎知识梳理
win10打印服务无法启动(运行时错误automation)
重磅大咖来袭!阿里云生命科学与智能计算峰会精彩内容剧透
Rust 从入门到精通03-helloworld
向量点积(Dot Product),向量叉积(Cross Product)
armv7与armv8的区别(v8和w12的区别)
使用scrapy 把爬到的数据保存到mysql 防止重复
刷题错题录1-隐式转换与精度丢失
List-based queuing and calling system
The perceptron perceptron of Li Hang's "Statistical Learning Methods" notes
用了TCP协议,就一定不会丢包嘛?
function call to print lua internal structure
The heavyweights are coming!Spoilers for the highlights of the Alibaba Cloud Life Science and Intelligent Computing Summit
yolov7 innovation point
php组件漏洞
8月份的.NET Conf 活动 专注于 .NET MAUI