Symbol 是唯一的 不能运算 对比


作用: 给对象 添加属性 和 方法 , 是独一无二的

// 创建 symbol
			// 1.
			let newSymbol = Symbol();
			console.log(newSymbol,typeof newSymbol)
			
			//2.
			let newSymbol1 = Symbol('hello world');
			console.log(newSymbol1,typeof newSymbol1)
			// Symbol.for 创建 (newSymbol2 === newSymbol3 true)
			let newSymbol2 = Symbol.for('hello world');
			let newSymbol3 = Symbol.for('hello world');
			console.log(newSymbol2,typeof newSymbol1)
			
			
			/* 给对象 添加方法(唯一 方法 (不确定)) */
			let game = {
				name : 'hello',
				up : function(){return 'hello world'}
			}
			// 当使用 原始赋值 (这样会 顶替掉原先的数据 如果这样 不安全)
			game.up = function(){return false}
			// 使用Symbol 添加 
			let method = {
				up : Symbol(),
				down : Symbol()
			}
			game[method.up] = function(){
				return "mySelf"
			}
			console.log(game.up())
			// 调用
			console.log(game[method.up]())
			
			/* 直接添加 */
			let youxi = {
				name : 'lol',
				[Symbol('say')] : function(){return 0}
			}
			// 遍历对象
			let arr = Reflect.ownKeys(youxi) // 将对象的 key 值赋值到 数组
			console.log(youxi[arr[0]])
			console.log(arr[1])
			console.log(youxi[Symbol('say')])
			/* Symbol 对象值 (Symbol 内部的属性)
				1.Symbol对象值  作为对象的属性存在,在特定的 情况下 会被触发(扩展了 对象功能)。
				
			*/

Symbol 对象值 :

Symbol对象值 作为对象的属性存在,在特定的 情况下 会被触发(扩展了 对象功能)。

举例 :

迭代器 Symbol.iterator 遍历操作 接口:

功能 :只要 部署了 Symbol.iterator 属性 就可以进行遍历操作

源生数据结构 具备此 接口(接口 : 对象中的一个属性):
String
Array
Arguments
Set
Map
String
TypedArray
NodeList

实现原理:

1.创建指针对象 指向 当前 数据结构的起始位置

2.第一次调用对象next 方法, 指针自动只想 数据结构第一个成员

3.接下来 不断调用next 知道最后一个成员

4.没调用next 方法 返回一个包含value done 属性对象

5.当done : true 时标志循环结束

代码实现:(实现 …object 返回每个value值)

实现思路 :

1. 先给对象 添加 Symbol.iterator 迭代器接口

2. return 一个对象 ,对象中存在 next 方法

3.开始遍历 对象 当 还有值时 返回对象 { value : value , done : false }

4. 当遍历完成 返回 { done : true } 结束遍历

			let obj = {
				name : '小张',
				age : 18,
				sex : '男'		
			}
			// 对象 新增迭代器接口
			// 1. 返回 一个next 对象  
			obj[Symbol.iterator] = function(){
				let index = 0
				return {
					next : () => {
						// 遍历 对象
						let arr = Reflect.ownKeys(this)
						let arrKey = this[arr[index]]
						if(index < arr.length - 1){
							index ++
							return {
								value : arrKey,
								done : false
							}
						}
						return {
							value : undefined,
							done : true
						}
					}
				}
			}
					
			console.log(...obj) // 解决 Found non-callable @@iterator

作者 译文

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注