学习vue源码的过程中,发现尤大经常给类的实例加上了唯一的id,后期判断或者添加的时候非常便捷,我觉得是个很好的技巧,本文就说下这个小技巧。
怎么分配id
其实分配id,操作起来很简单,如下所示就搞定了
let id = 0
class Dog{
constructor(){
this.id = ++id
}
}
// {id:1},{id:2}
console.log(new Dog,new Dog)
分配id的好处
分配id的好处,当有个列表里面装很多实例的时候,
- 方便去重
- 方便判断某个实例在不在其中
- 容易根据创建的顺序进行排序
- 即便所有的属性相同,但
id始终是不同的,方便调试
// 一个人可能养好几只狗
class Person{
constructor(){
this.dogs = []
this.dogsId = []
}
addDog(dog){
const hasDog = this.dogsId.includes(dog.id)
if(!hasDog){
this.dogs.push(dog)
this.dogsId.push(dog.id)
}
}
sortDog(){
this.dogs.sort((x,y)=>x.id-y.id)
this.dogsId.sort((x,y)=>x.id-y.id)
}
}
const dog1 = new Dog()
const dog1Copy = {...dog1}
const person1 = new Person()
const dog2 = new Dog()
person1.addDog(dog2)
person1.addDog(dog1)
person1.addDog(dog1Copy)
person.sortDog()
// {dogs:[dog1,dog2],dogIds:[2,1]}
console.log(person1)
这里如果有基础的话,就会知道在没有id的情况下,也可以this.dogs.include(dog),这种缺点是没那么直观,复制的话,也不会区别。
分配id的场景
当然不需要列表存实例的话,其实不需要增加id的。
只有一些特定的场景,需要实例列表,而且强调唯一性的话,就可以考虑下。
这边看下vue这边的id使用:
let uid = 0
class Dep{
constructor(){
this.id = uid++
}
}
class Watcher{
constructor(){
this.newDepIds = new Set()
this.newDeps = []
}
addDep (dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
}
}
}