首页 > 解决方案 > 如何访问点击处理函数中的函数?

问题描述

我使用纯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 作为参数传递给类,并使用 Select.call() SelectFeature 中的方法作为构造函数。

这是 ol.interaction.Select 类的描述

ol.interaction.Select 类有一个名为 getFeatures() 的成员。当单击某些 DOM 元素时,我尝试访问此方法(此块在 SelectFeature 类中):

$("#popupFeat-closer").click(function () {
    this.getFeatures();
});

当点击 DOM 元素时,上面的代码被触发,但是,在这一行:

this.getFeatures();

我收到此错误:

Uncaught TypeError: this.getFeatures is not a function

我的问题是如何访问位于 click 事件处理程序中的 getFeatures 函数?

标签: javascriptclientopenlayers

解决方案


就像评论中提到的那样,您遇到了上下文问题。几乎每个库或框架都有一个方法来保存上下文,在 jQuery 中你可以用proxy方法来实现。像这样的东西应该工作,

$("#popupFeat-closer").click($.proxy(function () {
    this.getFeatures();
}), this);

我会说使用库/框架解决这些问题总是好的,但是“旧”方法也可以,

var self = this;
$("#popupFeat-closer").click(function () {
    self.getFeatures();
});

jQuery Docs - 代理


推荐阅读