未捕获的TypeError:无法读取属性' addClass'

时间:2017-07-24 04:19:44

标签: javascript

我一直收到这个错误:

Uncaught TypeError: Cannot read property 'addClass' of undefined
    at HTMLButtonElement.openMenuDeserts (App.js:135)
    at HTMLButtonElement.dispatch (App.js:5354)
    at HTMLButtonElement.elemData.handle (App.js:5162)

这是我的代码:

import $ from 'jquery';

class MenuDeserts {
  constructor() {
    this.openMenuButton = $(".open-menu-deserts");
    this.Deserts = $("#desertMenu");
    this.events();
  }

  events() {
    this.openMenuButton.click(this.openMenuDeserts);
  }


  openMenuDeserts() {
    this.Deserts.addClass("menu-deserts--is-visible");
    return false;
  }

}

export default MenuDeserts;

如果我替换" openMenuDeserts(){}"的内容使用console.log它将显示在控制台中,但无论我放在那里我都会收到该错误。有什么建议吗?

2 个答案:

答案 0 :(得分:0)

当click事件最终发生并且jQuery调用openMenuDeserts()时,this的值未设置为您的对象,它被设置为发生click事件的DOM元素。使用.bind()确保使用正确的this值调用您的函数:

events() {
  this.openMenuButton.click(this.openMenuDeserts.bind(this));
}

答案 1 :(得分:0)

在事件功能上,您正在尝试使用您的功能绑定点击事件。 click事件将被触发,但openMenuDeserts函数的问题没有绑定到MenuDeserts。最佳做法是将您的功能绑定到"这个"构造函数中的类的实例。

import $ from 'jquery';

class MenuDeserts {
  constructor() {
    this.openMenuButton = $(".open-menu-deserts");
    this.Deserts = $("#desertMenu");
    this.events();
    // bind the function to this in constructor
    this.openMenuDeserts.bind(this);
  }

  events() {
    this.openMenuButton.click(this.openMenuDeserts);
  }


  openMenuDeserts() {
    this.Deserts.addClass("menu-deserts--is-visible");
    return false;
  }

}

export default MenuDeserts;


There are 3 ways you can solve this issue:
1) bind the function to "this" instance in constructor of the class.
2) bind the function to "this" instance on where you triggering the function. 
Ex: 
    this.openMenuButton.click(this.openMenuDeserts.bind(this));

Note: This is will trigger bind every time the click is triggered.

3) Use fat Arrow function in click.
Ex: 

this.openMenuButton.click(()=> {
       this.openMenuDeserts()
   });