我正在学习JavaScript并尝试扩展一个Map
。我做了以下操作:
function mapExtend(mapInstance) {
function MapExtend(){
}
MapExtend.prototype = Object.create(Map.prototype);
MapExtend.prototype.constructor = MapExtend;
return new MapExtend(mapInstance)
}
我做了这个:
const b = new Map()
mapExtend(b).get(1)
我遇到了以下错误:
Uncaught TypeError: Method Map.prototype.get called on incompatible receiver #<MapExtend>
at MapExtend.get (<anonymous>)
at <anonymous>:1:14
我在这里犯了什么错误?
MapExtend
对象的实例上下文中调用Map
的构造函数(Map.apply(this, arguments)
),我想它会起作用。我猜它会做一些必要的初始化,但现在我无法确认这个假设。但是调用构造函数不起作用,因为引擎会抱怨构造函数只能使用new
来调用。 - t.niese