【问题标题】:Prototype Class.create not subclassing properly原型 Class.create 没有正确子类化
【发布时间】:2011-03-04 19:53:08
【问题描述】:

所以,我正在尝试扩展一个谷歌地图类,特别是 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
    }

但是,以原型方式进行,无法添加任何父类方法:

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)
    );

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

显然,这没什么大不了的,但我想知道是否有其他人遇到过这个问题,以及它是否很容易纠正。我正在使用原型 1.7。

【问题讨论】:

  • 我想知道父类是否必须是由Prototype自己的系统创建的......

标签: javascript oop prototype


【解决方案1】:

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

来自prototype's class.js

[[Class.create]] 接受两种参数。如果第一个参数是 a [[Class]],它被用作新类的超类,它的所有 方法是继承的。否则,任何传递的参数都被视为 对象,并且它们的方法作为实例方法被复制(“混合”) 新班级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多