繁体   English   中英

关联数组中的Javascript函数“不是函数”

[英]Javascript functions in associative array "is not a function"

最近我了解到 Javascript ES6 有类,所以我尝试了它们,但我的函数总是给我错误,说它们不存在。 所以我使用 javascript 关联数组制作了伪类。 在我添加了一些新方法之前,它工作得非常好

这是我收到的错误消息:

EventListener.js:132 Uncaught TypeError: this.listen_for_tab_swap is not a function
at HTMLDivElement.<anonymous> (EventListener.js:132)
at Object.alert_eventlistener_of_tabs (EventListener.js:41)
at Object.new_tab (EventListener.js:59)
alert_eventlistener_of_tabs @ EventListener.js:41
new_tab @ EventListener.js:59
xhr.onreadystatechange @ EventListener.js:94
XMLHttpRequest.send (async)
(anonymous) @ EventListener.js:101

这是相关的代码体:

const eventListener = {

     listen_for_tab_swap: function() {
         $(".footer button").on("click", function (event) {
             file_tabs.show_tab(event.target.innerText);
         });
     },

     listen_for_tabs_activation: function() {
         $("#AZ_content").on("tabs_loaded", function () {
             this.listen_for_tab_swap();
         });
     },

     listen: function() {
         $(function () {
             console.log("Yeah, I'm listening...");
             $(".menu").on("click", function (event) {
                 AZ_page_is_opened(event);
                 showTab(event, event.target.id.replace("Button", ""));
             });
         });
     }
 };

请让我知道是否需要任何其他信息来进行故障排除。 在此先感谢您的帮助。

在 js 中, this是动态的。 这取决于函数的调用方式。 我假设您正在使用 jQuery,因为它看起来像 jQuery 语法一目了然,因此对于您的特定情况,您需要知道的是,在 jQuery(以及常规 javascript)中,onclick 事件中this的值是元素触发事件:

{
  // ...

  listen_for_tabs_activation: function() {
     $("#AZ_content").on("tabs_loaded", function () {
         this.listen_for_tab_swap(); // this is AZ_content
     });
}

在上面的代码中,您正在尝试调用$("#AZ_content")[0].listen_for_tab_swap()并且抱怨该 HTML 元素没有名为listen_for_tab_swap的方法

有几种方法可以解决这个问题。 最简单的可能是:

eventListener.listen_for_tab_swap();

您还可以使用箭头函数来绑定this

{
  // ...

  listen_for_tabs_activation: function() {
     $("#AZ_content").on("tabs_loaded",() => { // this fixes `this`
         this.listen_for_tab_swap();
     });
}

还有几种方法可以解决这个问题。 查看另一个相关问题的答案,了解this实际行为: Javascript 中的“this”关键字如何在对象文字中起作用?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM