1

I am trying to create a custom Google maps object which uses prototype inheritance to proxy any functions it does not have through to the Google Maps object.

So far this is an extremely simple example of what I am trying to achieve:

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

This works fine but I am overriding the prototype of my MapProxy and therefore I have to define my functions as this.myFunction inside my constructor. Instead of it being a reference now every Google maps instance creates it's own custom functions.

Now I probably won't end up with 15 Google Map instances but is there a better strategy to inherit the prototyped functions of the Google Maps object without overriding my ProxyMap prototype functions?

4

1 回答 1

1

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

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;
    }
}
于 2018-01-26T12:59:48.767 回答