我对提出老问题表示歉意,但我发现了一个非常有趣的解决办法,由以下网站启发:Bergi swer和提到,不可能。
class PairKey {
private static cache: Record<string, PairKey> = {};
constructor(
private _x: number, private _y: number,
action: create | read | delete = read
) {
const key = PairKey.key(_x, _y);
if (action === create || action === read ) {
if (PairKey.cache[key]) {
return PairKey.cache[key];
}
if (action === create ) {
PairKey.cache[key] = this;
}
}
else if (action === delete ) {
delete PairKey.cache[key];
}
}
private static key(x: number, y: number) {
return `${x}_${y}`;
}
get x() {
return this._x;
}
set x(x_pos: number) {
this._x = x_pos;
}
get y() {
return this._y;
}
set y(y_pos: number) {
this._y = y_pos;
}
}
const allElem = new Map<PairKey, string>();
allElem.set(new PairKey(1, 2, create ), a ); // the action flag to prevent a memory leak
allElem.set(new PairKey(2, 3, create ), b ); // the action flag to prevent a memory leak
console.log(allElem.has(new PairKey(1, 2))); // Returns true
allElem.delete(new PairKey(1, 2, delete )); // the action flag to prevent a memory leak
console.log(allElem.has(new PairKey(1, 2))); // Returns false
类似解决办法,静态更强:
class PairKey {
private static cache: Record<string, PairKey> = {};
private static readonly symbol = Symbol();
private constructor(private _x: number, private _y: number, symbol: symbol) {
if (symbol !== PairKey.symbol) {
throw new Error("Use PairKey.create() instead of constructor");
}
}
static create(x: number, y: number) {
const key = PairKey.key(x, y);
if (PairKey.cache[key]) {
return PairKey.cache[key];
}
const pairKey = new PairKey(x, y, PairKey.symbol);
PairKey.cache[key] = pairKey;
return pairKey;
}
static read(x: number, y: number) {
const key = PairKey.key(x, y);
return PairKey.cache[key];
}
static delete(x: number, y: number) {
const key = PairKey.key(x, y);
const pairKey = PairKey.cache[key];
delete PairKey.cache[key];
return pairKey;
}
private static key(x: number, y: number) {
return `${x}_${y}`;
}
get x() {
return this._x;
}
set x(x_pos: number) {
this._x = x_pos;
}
get y() {
return this._y;
}
set y(y_pos: number) {
this._y = y_pos;
}
}
const allElem = new Map<PairKey, string>();
allElem.set(PairKey.create(1, 2), a );
allElem.set(PairKey.create(2, 3), b );
console.log(allElem.has(PairKey.read(1, 2))); // Returns true
allElem.delete(PairKey.delete(1, 2));
console.log(allElem.has(PairKey.read(1, 2))); // Returns false