如何在事件绑定中访问对象方法

时间:2018-10-04 05:16:29

标签: javascript

(function() {
  let create = {

    init() {
      this.cacheDom();
      this.bindEvent();
    },

    bindEvent() {
      $(this.$content_buttons).click(function() {
        create.preformAction(this);
      });
    },

    cacheDom() {
      this.$content_buttons = $('.content_button');
    },

    preformAction(el) {
      alert('its class is ' + $(el).attr('class'));
    }
  };
  create.init();
}());

考虑上面的代码,我可以通过执行 create.performAction 来访问 create 对象的 performAction 方法。还有其他方法吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

尝试:

(function() {
 let create = {

init() {
  this.cacheDom();
  this.bindEvent();
},

bindEvent() {

  $(this.$content_buttons).click(function() {
    create.preformAction(this);
  });
},

cacheDom() {
  this.$content_buttons = $('.content_button');
},

preformAction(el) {
  alert('its class is ' + $(el).attr('class'));
}
 };
  create.init();
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="content_button class1">click1</button>
<button class="content_button class2">click2</button>