javascript - 如何访问点击处理函数中的函数?
问题描述
我使用纯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 函数?
解决方案
就像评论中提到的那样,您遇到了上下文问题。几乎每个库或框架都有一个方法来保存上下文,在 jQuery 中你可以用proxy
方法来实现。像这样的东西应该工作,
$("#popupFeat-closer").click($.proxy(function () {
this.getFeatures();
}), this);
我会说使用库/框架解决这些问题总是好的,但是“旧”方法也可以,
var self = this;
$("#popupFeat-closer").click(function () {
self.getFeatures();
});
推荐阅读
- vue.js - vue v-for 在循环中重新渲染一个循环
- vhdl - 使用 Vivado 将函数的返回值分配给 VHDL 中的多维数组失败
- python - Python,在随机索引处向向量添加值的最有效方法是什么?
- javascript - 如何动态更新物化
- azure - 通过“transit”vNet 向本地服务发出请求
- android - DiffUtil 不应该与 hashCode 进行比较吗?
- python - 如何遍历一系列子图中的轴元素?
- image - 为什么这个 jpeg 图像在不同平台上呈现的颜色略有不同?
- java - 减少 switch 语句的耦合
- hl7-fhir - FHIR forge 来自基本类型的配置文件元素