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?

Stephan-v
  • 19,255
  • 31
  • 115
  • 201

1 Answers1

1

Uh, since you're using ES6 class syntax anyway, why not use it for inheritance as well?

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;
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks this works, what would be the ES5 equivalent for this though? I am curious since my example is kind of a hybrid. – Stephan-v Jan 26 '18 at 13:03
  • @Stephan-v [Just the usual](https://stackoverflow.com/a/15192747/1048572). If you're not sure, pass the ES6 through a transpiler :-) – Bergi Jan 26 '18 at 13:17