ajax数据选项中的此上下文

this context in ajax data option

本文关键字:上下文 数据 选项 ajax      更新时间:2023-09-26

我有一个带有data数组和mark_read方法的对象,它将PUT请求发送到我的Rails应用程序。看起来data选项中的this不是对象实例,我该如何修复它?

Notifications.prototype = {
  constructor: Notifications,
  ...
  mark_read: function() {
    $.ajax({
      method: "PUT",
      url: '/notifications/mark_read',
      data: this.data.slice(0,5)
    });
  }
  ...
}

在尝试从$.ajax函数内部访问它之前,应该将"this"存储在闭包中。

应该是像这个

Notifications.prototype = {
  constructor: Notifications,
  ...
  mark_read: function() {
      var me = this;
      $.ajax({
          method: "PUT",
          url: '/notifications/mark_read',
          data: me.data.slice(0,5)
      });
  }
  ...
}

this的作用域是mark_read函数,因此this的上下文是调用Notification对象mark_read()的任何对象。