Search code examples
javascriptleafletextend

How does extending work in LeafletJS and why do I need an intermediary attribution for it to work correctly?


First of all, this might not be a LeafletJS question, but a mere JS one, but I haven't come across it until Leaflet.

I've been experimenting with Leaflet lately and at some point wanted to pass to a function an extended version of a Control object (for those who also work with Java or similar language, I was trying to do something similar with instantiating an anonymous class).

So:

Given the class L.Control (which I wanted to extend with the method x), I tried:

func(new L.Control.extend({x: function() {}})());

which fails miserably, because the parameter of the function func is undefined.

However:

var v = L.Control.extend({x: function() { }}); 
func(new v());

works perfectly, as new v() returns, as expected, a L.Control object with an extra x function.

Bottom line: what is the difference between the 2 snippets of code and how can I make it work with a one-liner (if possible)?

Thanks!


Solution

  • After some experiments, I figured it out by myself.

    The problems is due to the order of operations and the solution was to add a set of brackets, the one-liner becoming:

    func(new (L.Control.extend({x: function() {}}))());