次文章仅为自己学习和记录使用
1.当一个对象中声明了属性或者方法时,在需要添加相同的属性或者方法可以使用到symbol唯一值
第一种方式:在这段代码中name中已经存在up 和down属性 而我继续向name中添加属性 如果没有预先使用symbol创建 则会报错
let name = {
youxi: "狼人杀",
up: "哈哈",
down: "你好",
}
let methods = {
up: Symbol(),
down: Symbol(),
}
name[methods.up] = function () {
console.log("qwe")
}
name[methods.down] = function () {
console.log("hhahh")
}
console.log(name)
第二种方式:可以直接在symbol的参数中书写属性/方法名
let youxi = {
name: "lol",
[Symbol("say")]: function () {
console.log("我是lol")
},
}
console.log(youxi)
迭代器/接口 (工作原理)
let num = {
name: "动漫人物",
person: ["索隆", "祢豆子", "蝴蝶忍"],
[Symbol.iterator]: function () {
let index = 0 //索引下标
return {
next: () => {
if (index < this.person.length) {
const res = { value: this.person[index], done: false }
index++
return res
} else {
return { value: "undefined", done: true }
}
},
}
},
}
for (const key1 of num) {
console.log(key1) //num is not iterable
}
上面代码 是 我自定义我要拿到的数据 符合面向对象编程思维 而不是使用对象方法 比如我是需要拿到person中的value值 直接使用 for...of 则会报错 TypeError: num is not iterable 显然是不行的
这时候可以使用迭代器进行处理 因为 iterator 是symbol的一个属性可直接调用 而symbol也是对象或者数组的一个属性 这时候直接加上Symbol.iterator方法(也称为接口) 保存 会直接看到后台提示
TypeError: Result of the Symbol.iterator method is not an object 这是因为该方法工作原理是必须返回一个对象 必须是next(){} 函数 添加后 会提示 Iterator result undefined is not an object 原因是必须有返回值 且为 {value:'',done:false}形式 这时候 因为next方法会一直走一下 当done的值为false时会一直循环下去 (可看工作原理) 而这时候我们就可以在这里处理我们要的数据 注意this的问题 可使用箭头函数 或者 普通函数 声明this 处理完后 并返回结果 这个时候我们就可以使用for...of拿到我们想要的数据