【问题标题】:How to extend the Google maps class?如何扩展谷歌地图类?
【发布时间】:2018-07-05 19:27:33
【问题描述】:

我正在尝试创建一个自定义 Google 地图对象,该对象使用原型继承将它没有的任何功能代理到 Google 地图对象。

到目前为止,这是我想要实现的一个非常简单的示例:

export default class MapProxy {
    constructor(element, options) {
        this.markers = {};
        google.maps.Map.apply(this, arguments)]
    }

    this.hasMarkers = () => {
        return (Object.keys(this.markers).length > 0);
    };
}

MapProxy.prototype = Object.create(google.maps.Map.prototype);

这工作正常,但我覆盖了我的 MapProxy 的原型,因此我必须在我的构造函数中将我的函数定义为 this.myFunction。现在每个 Google 地图实例都创建了自己的自定义函数,而不是作为参考。

现在我可能不会得到 15 个 Google Map 实例,但有没有更好的策略来继承 Google Maps 对象的原型函数而不覆盖我的 ProxyMap 原型函数?

【问题讨论】:

    标签: javascript inheritance ecmascript-6 prototype proto


    【解决方案1】:

    呃,既然你使用的是 ES6 class 语法,为什么不把它也用于继承呢?

    export default class MapProxy extends google.maps.Map {
    //                            ^^^^^^^^^^^^^^^^^^^^^^^
        constructor(element, options) {
            super(...arguments);
            this.markers = {};
            // own method as an arrow function initialised in the constructor
            this.hasMarkers = () => Object.keys(this.markers).length > 0;
        }
        // prototype method
        hasMarkers() {
            return Object.keys(this.markers).length > 0;
        }
    }
    

    【讨论】:

    • 感谢这项工作,但是 ES5 的等效项是什么?我很好奇,因为我的例子是一种混合体。
    • @Stephan-v Just the usual。如果您不确定,请通过转译器传递 ES6 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 2018-11-12
    • 2017-12-27
    • 2019-06-02
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多