面向对象的javascript - 这个[function]不是一个函数

时间:2017-05-18 20:15:20

标签: javascript jquery

我正在将一些jquery函数移动到javascript对象中以清理一些代码。我的问题是,当我将方法放在我的对象的构造函数上时,调用this.functionName is not a function会返回错误function MyConstructor() { this.init(); this.selectAllHandler(); } MyConstructor.prototype = { init: function() { var self = this; $(document).on('click', '#my_element', function() { self.selectAllHandler.call(this); }); }, selectAllHandler: function() { // handler works fine var ids_array = this.idsArray(checkboxes); // error happening here }, // helpers idsArray: function(checkboxes) { // trying to call } } 但是如果我的函数是辅助方法并且在对象的构造函数之外,他们工作得很好。

这是我的代码不起作用

function MyConstructor() {
    this.init();
}

MyConstructor.prototype = {
  init: function() {
    var self = this;
    $(document).on('click', '#my_element', function() {
      self.selectAllHandler.call(this);
    });
  },
  selectAllHandler: function() {
    // handler works fine
    var ids_array = idsArray(checkboxes);
  }
}

function idsArray() {
  // code that works fine
}

但是,让我的对象使用构造函数,然后调用" helper"对象外面工作正常。例如,这很好。

this

有一点需要注意的是,在这种情况下,通过运行console.log call引用被单击的元素,而不是构造函数。

我已尝试使用applybindEXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x00000028 ,但未取得成功,但我认为它与语法相关。

我如何建立这个,所以我可以打电话给我的帮助"我的对象里面的函数?

2 个答案:

答案 0 :(得分:0)

不确定您使用bind的方式,因为您说它不适合您。 如果需要,可以使用如下所示的绑定。此外,您的代码段checkboxes未定义。这样您就不需要使用self

function MyConstructor() {
  this.init();
  this.selectAllHandler();
}

MyConstructor.prototype = {
  init: function() {
    //var self = this;
    $(document).on('click', '#my_element', function() {
      //self.selectAllHandler.call(self);
      this.selectAllHandler();
    }.bind(this));
  },
  selectAllHandler: function() {
    // handler works fine
    var checkboxes;
    var ids_array = this.idsArray(checkboxes); // error happening here
  },
  // helpers
  idsArray: function(checkboxes) {
    // trying to call
    console.log('test');
  }
}

var o = new MyConstructor();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:-1)

我能够弄清楚。我以为我可以使用this.functionName()在构造函数中调用另一个函数。但是,$(this)指的是我点击的元素。

我记得我在我的init函数中定义了self (this),它引用了window对象。好吧,window对象里面是我的对象,我的函数在那个对象上。所以我能够通过

成功调用我的对象
function MyConstructor() {
    this.init();
}

MyConstructor.prototype = {
  init: function() {
  var self = this;
    $(document).on('click', '#my_element', function() {
        self.selectAllHandler.call(this);
    });
  },
  selectAllHandler: function() {
    // RIGHT HERE
    var ids_array = self.MyConstructor.prototype.idsArray(checkboxes);
  },
  // helpers
  idsArray: function(checkboxes) {
    // some codes
  }
}