有一个API(具体来说是d3.map
),它实现了size
方法。不过,我想扩展它,以便它保持向后兼容,但它也可以用作值访问器/ getter (因为这就是它现在在 ES6
中指定的方式):
var map = d3.map();
map.set(0, 1);
console.log(map.size()); // Old code, should still work
xhr.send(JSON.stringify(map.size)); // Should also work (as a getter)
这可能吗?
最佳答案
没有办法做你喜欢的事。
唯一的出路是将 size()
替换为 getSize()
class Map{
public get size(){
return 1;
}
public set size(size:number){
}
getSize():number{
return 1;
}
}
更新
只有一个解决方案。只需使用 key 长度来实现新功能,并使用 key 大小来实现向后兼容性。它看起来像一个 C# List
类。
class Map {
private count = 0;
public get length(): number {
return this.count;
}
public set length(length: number) {
this.count = length;
}
public size(): number;
public size(size: number): void;
public size(size?: number): any {
if (size) {
this.count = size;
} else {
return this.count;
}
}
}
你的例子
var map = d3.map();
map.set(0, 1);
console.log(map.size()); // Old code, should still work
xhr.send(JSON.stringify(map.length)); // Should also work (as a getter)
关于javascript - 在既是值访问器又是函数的对象上定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883821/