对象原型无法识别功能

时间:2016-06-10 06:59:36

标签: javascript

我在对象原型上有3个函数:

Job.prototype.postData = function(url) {
  this.getFormData();
  var formdata = new FormData();
  formdata.append("position", this.position);
  formdata.append("team", this.team);
  formdata.append("details", this.details);
  $.post(url, formdata, function(response) {
    alert(response.message);
    window.location.href = '/';
  });
};

Job.prototype.createNew = function() {
  var newUrl = API_URL + "/add_listing";
  this.postData(newUrl)
};

Job.prototype.update = function() {
  var updateUrl = API_URL + "/edit_listing" + "?id=" + this.id;
  this.postData(updateUrl)
};

我将最后两个作为事件处理回调附加:

$('#list-button').on('click',job.createNew);
$('#list-button').on('click',job.update);

这两个都提供TypeError

  

oop.js:38 Uncaught TypeError: this.postData is not a function

1 个答案:

答案 0 :(得分:1)

问题很简单,$_FILES上下文会因为绑定事件处理程序而丢失。

显式this上下文,或以保留上下文的方式调用函数:

bind

请参阅How does the "this" keyword work?