Javascript回调的范围问题

Javascript回调的范围问题

本文介绍了Javascript回调的范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦让回调函数工作。这是我的代码:

I am having some trouble getting a callback function to work. Here is my code:

SomeObject.prototype.refreshData = function()
{
  var read_obj = new SomeAjaxCall("read_some_data", { }, this.readSuccess, this.readFail);
}

SomeObject.prototype.readSuccess = function(response)
{
    this.data = response;
    this.someList = [];
    for (var i = 0; i < this.data.length; i++)
    {
      var systemData = this.data[i];
      var system = new SomeSystem(systemData);
      this.someList.push(system);
    }
    this.refreshList();
}

基本上SomeAjaxCall正在对数据进行ajax请求。如果它工作,我们使用回调'this.readSuccess',如果它失败'this.readFail'。

Basically SomeAjaxCall is making an ajax request for data. If it works we use the callback 'this.readSuccess' and if it fails 'this.readFail'.

我已经弄清楚'this'在SomeObject.readSuccess是全局的(也称为窗口对象),因为我的回调被称为函数,而不是成员方法。我的理解是,我需要使用闭包来保持'这'周围,但是,我不能得到这个工作。

I have figured out that 'this' in the SomeObject.readSuccess is the global this (aka the window object) because my callbacks are being called as functions and not member methods. My understanding is that I need to use closures to keep the 'this' around, however, I have not been able to get this to work.

如果有人能告诉我我应该做什么,我会很感激。我仍然围绕着闭包如何工作,特别是如何在这种情况下工作。

If someone is able show me what I should be doing I would appreciate it greatly. I am still wrapping my head around how closures work and specifically how they would work in this situation.

谢谢!

推荐答案

最简单的方法是在另一个函数中包装this.readSuccess:

Well the most straightforward thing to do is to just wrap "this.readSuccess" in another function:

SomeObject.prototype.refreshData = function()
{
  var obj = this;
  var read_obj = new SomeAjaxCall("read_some_data", { },
    function() { obj.readSuccess(); }, function() { obj.readFail(); });
}

一些Javascript框架提供了一个实用程序来这意味着它为你创造了一个小功能。注意,变量obj将被那些小函数记住,因此当你的处理程序被调用时,this引用将被用于调用refreshData的对象。

Some Javascript frameworks provide a utility to "bind" a function to an object, which simply means that it creates one of those little functions for you. Note that the variable "obj" will be "remembered" by those little functions, so when your handlers are called the "this" reference will be to the object that was used to call "refreshData".

这篇关于Javascript回调的范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:04