javascript - 初始化后如何访问类的成员?

标签 javascript web client openlayers

我使用纯 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));

如您所见,我将 ol.interaction.Select 作为参数传递给该类,并使用 SelectFeature 中的 Select.call() 方法作为构造函数。

这里是 ol.interaction.Select 类的描述。

ol.interaction.Select 类有一个名为 on() 的成员。我尝试像上面的示例中这样访问此方法:

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

但我收到此错误:

Uncaught TypeError: this.on is not a function

我的问题是如何访问 ol.interaction.Select 类的成员?

最佳答案

thisSelectFeature 函数之外没有定义。 因此,您需要在 SelectFeature 函数内调用 this.on 。 为此,您需要在 SelectFeature 函数内部设置 on 函数:

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

关于javascript - 初始化后如何访问类的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60893894/

相关文章:

javascript - npm csv-parse 不读取所有行

python - 如何在 Beautiful Soup 4 (Python) 中使用搜索栏

java - 与 Java 服务器的 PHP tcp 连接在 socket_read() 上挂起

c# - 使用 msbuild 从网站部署中排除文件

android - 如何使用wifi p2p将数据从组所有者发送到客户端

android - Google Api 客户端 NoClassDefFoundError ApacheHttpTransport

Javascript RegEx 使用全局修饰符产生不寻常的结果

php - Spotify 创建播放列表 API php

php - 在两个单词之间包含空格 Javascript if() 语句

javascript - CSS Flex 与手动 JavaScript 计算的性能对比