gpt4 book ai didi

javascript - Prototype Class.create 没有正确地子类化

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:21:54 24 4
gpt4 key购买 nike

所以,我正在尝试扩展一个谷歌地图类,特别是 google.maps.OverlayView(在 v3 中)。以 vanilla js 的方式完成它完全有效。

POIOverlay = function(marker, poi, type)
{
this._marker = marker;
this._poi = poi;
this._type = type;
this._div = null;
this.latlng_ = marker.getPosition();
this._map = marker.getMap();
this._offsetVertical = -195;
this._offsetHorizontal = 0;
this._height = 165;
this._width = 266;
}
POIOverlay.prototype = new google.maps.OverlayView();
POIOverlay.prototype.create = function()
{
console.log(this)
}
POIOverlay.prototype.draw = function()
{
//stuff
}

但是,以原型(prototype)方式进行操作,无法添加任何父类方法:

POIOverlay = Class.create(new google.maps.OverlayView(), {
initialize : function(marker, poi, type)
{
this._marker = marker;
this._poi = poi;
this._type = type;
this._div = null;
this.latlng_ = marker.getPosition();
this._map = marker.getMap();
this._offsetVertical = -195;
this._offsetHorizontal = 0;
this._height = 165;
this._width = 266;
},
create : function()
{
if(this._div) return;
console.log(this);
},
draw : function()
{
//stuff
}
});

下面是实例化/使用类的代码:

    try
{
poio = new POIOverlay(marker,poi,type);
}
catch(e)
{
console.log(e);
}

google.maps.event.addListener(marker, 'click',
poio.draw.bind(poio)
);

在第一个示例中,控制台记录了一个具有父子方法/属性的对象。在第二个示例中,控制台记录了一个没有父属性/方法的对象。

显然,这不是什么大问题,但我想知道是否有其他人遇到过这个问题,是否可以轻松解决。我正在使用原型(prototype) 1.7。

最佳答案

父类(super class)参数需要是一个适当的原型(prototype)“类”——记住类在 JavaScript 中并不真正存在。 JavaScript 有几种经典的继承模式,您应该能够通过手动代理构造函数和原型(prototype)来获取原型(prototype)链(包括对父“类”及其原型(prototype)的引用)。

来自 prototype's class.js :

[[Class.create]] accepts two kinds of arguments. If the first argument is a [[Class]], it's used as the new class's superclass, and all its methods are inherited. Otherwise, any arguments passed are treated as objects, and their methods are copied over ("mixed in") as instance methods of the new class.

关于javascript - Prototype Class.create 没有正确地子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5198554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com