javascript - 在原型(prototype)中调用函数

标签 javascript jquery

我开始学习 JavaScript 中的 OOP,并遇到了这个问题。 我有一个简单的对象:

function Notifications() {
  this.button = $('#dLabel');
  this.wrapper = $('#notifications');
  this.elements = [];
}

Notifications.prototype = {
  constructor: Notifications,
  fetch: function() {
    $.ajax({
      method: "GET",
      url: '/notifications.json'
    }).done(function(data) {
      this.elements = data;
      this.refresh();
    });
  },
  refresh: function() {
    console.log("REFRESH");
  }
}


$(function() {
  var ns = new Notifications();

  ns.fetch();
})

当我运行这个时,我得到:

Uncaught TypeError: this.refresh is not a function

是不是因为.done函数中的this不是Notifications实例?我该如何解决这个问题?

最佳答案

使用bind() method修复上下文:

Notifications.prototype = {
  constructor: Notifications,
  fetch: function() {
    $.ajax({
      method: "GET",
      url: '/notifications.json'
    }).done(function(data) {
      this.elements = data;
      this.refresh();
    }.bind(this)); // <------- Use bind(this)
  },
  refresh: function() {
    console.log("REFRESH");
  }
}

done() 处理程序 function(data) {...} 作为一个简单的函数调用执行,它具有上下文 this 作为全局对象(窗口)或“严格模式” 中的未定义
Function.prototype.bind(newContent) 将上下文修改为 newContext

This section更详细地描述了 this 如何丢失以及如何防止丢失。

关于javascript - 在原型(prototype)中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083905/

相关文章:

javascript - 如何根据其他字段显示/隐藏列字段 - SharePoint

javascript - 这个 Javascript 语句(正则表达式)是什么意思?

javascript - 为什么这个表单验证失败后仍继续提交?

javascript - 选择选择下拉值时添加迄今为止的天数 JQuery/JS

javascript - 如何在div上制作悬停效果

javascript - 响应式菜单的子菜单在离开屏幕时不会强制滚动

javascript - HTML 图像呈现通知

javascript - Durandal 如何附加 View 并在准备好之前不显示它?

javascript - 每次呈现主干 View 时是否应该使用 jQuery 选择相同的元素

javascript - HTML 表单方法与 jQuery 函数类型