我正在使用 ES2015 map ,我发现它是一个很棒的功能。但是,我现在有一个用例,我不太确定是否可以使用 map 。
考虑我的类(class)
class A {
constructor(public a:number) {}
public equals(obj: A): boolean {
return this.a === obj.a;
}
}
据我所知,ES2015 map 将使用 === 相等运算符(有一些异常(exception))。因此我想知道是否有可能覆盖相等性并强制它使用 A
对象的 equals(...)
方法 if instanceof?
最终这就是我想要实现的:
var map = new Map();
map.set(new A(8), 7)
map.get(new A(8)) // return 7, not undefined
你认为我必须创建自己的 Map 类来实现这种检查两个对象是否都是 A
实例然后调用 equals(...)
的行为吗? > 方法?
最佳答案
您可以根据需要创建子类并覆盖 get
方法:
class MapByEquals extends Map {
get(key) {
for(var k of this.keys()) {
if(key.equals(k)) {
return super.get(k);
}
}
return super.get(key);
}
}
"use strict";
class A {
constructor(a) {
this.a = a;
}
equals(b) {
return this.a === b.a;
}
}
class MapByEquals extends Map {
get(key) {
for(var k of this.keys()) {
if(key.equals(k)) {
return super.get(k);
}
}
return super.get(key);
}
}
var map = new MapByEquals();
map.set(new A(8), 7)
console.log(map.get(new A(8)))
请注意,Babel 不支持原生类扩展。但是大多数浏览器(Chrome 42+、Firefox 45+)本身就支持类并且它会起作用。
关于javascript - 调整 ES2015 Map 以支持所需的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36107162/