EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

Map 中 Key 为对象的有趣问题 #81

Open EdwardZZZ opened 1 year ago

EdwardZZZ commented 1 year ago
const map = new Map();

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    return class extends constructor {
    }
}

function propertyDecorator(obj: any): PropertyDecorator {
    return function (target) {
        console.log(obj === Greeter);
        map.set(obj, 2);
    }
}

@classDecorator
class Greeter {
    @propertyDecorator(Greeter)
    hello: string;
}

class G {
    @propertyDecorator(Greeter)
    hello: string;
}

console.log(new G());
console.log(map);
true
true
G {}
Map(2) {
  [class Greeter] => 2,
  [class (anonymous) extends Greeter] => 2
}
EdwardZZZ commented 1 year ago
const map = new Map();
const o: any = {
    a: 1,
}

map.set(o, 1);
o.b = 2;
map.set(o, 2);

console.log(map);
console.log(o);
Map(1) { { a: 1, b: 2 } => 2 }
{ a: 1, b: 2 }