Search code examples
javascriptwebclientopenlayers

How to access the member of the class after initialization?


I create this class using pure javascript:

var SelectFeature = /*@__PURE__*/(function (Select) {
    function SelectFeature() {
        Select.call(this, {
            condition: ol.events.condition.click
        });
    }

    this.on('select', function (e) {
        //some logic
    });

    if (Select) SelectFeature.__proto__ = Select;
    SelectFeature.prototype = Object.create(Select && Select.prototype);
    SelectFeature.prototype.constructor = Select;

    return SelectFeature;
}(ol.interaction.Select));

as you can see I pass ol.interaction.Select as a parameter to the class and using Select.call() the method in SelectFeature as a constructor.

Here is a description of ol.interaction.Select class.

The ol.interaction.Select class has a member who is called on(). I try to access this method like this in the example above:

this.on('select', function (e) {
        //some logic
})

but I get this error:

Uncaught TypeError: this.on is not a function

My question is how can I access the on the member of the ol.interaction.Select class?


Solution

  • this has no definition outside of the SelectFeature function. So you need to call this.on inside the SelectFeature function. In order to do that you need to set the on function inside the SelectFeature function:

    var SelectFeature = /*@__PURE__*/(function (Select) {
        function SelectFeature() {
            Select.call(this, {
                condition: ol.events.condition.click
            });
            this.on = Select.prototype.on; // This gets Select's on method and gives it to `this`
            this.on('select', function (e) {
               //some logic
             });
        }
    
        if (Select) SelectFeature.__proto__ = Select;
        SelectFeature.prototype = Object.create(Select && Select.prototype);
        SelectFeature.prototype.constructor = Select;
    
        return SelectFeature;
    }(ol.interaction.Select));