Javascript对象和这个

mkl*_*kly 1 javascript ajax jquery this

function robot(robotId) {
  this.id = robotId;
  this.parts = new Array();

  this.collectParts = function() {
    $.getJSON('some/url', function(json) {
      for(i in json.responses) {
        this.parts = json.responses[i].parts;
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何实际分配this.parts?

JAA*_*lde 6

this为变量分配一个引用(当它在适当的范围内时)并在函数中使用该变量来改变范围this.在下面代码的修改版本中,robotInstance是我选择使用的变量:

function robot(robotId) {
  var robotInstance = this;

  this.id = robotId;
  this.parts = new Array();

  this.collectParts = function() {
    $.getJSON('some/url', function(json) {
      for(i in json.responses) {
        robotInstance.parts = json.responses[i].parts;
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:昨晚我写了这个修改,然后决定不发布.但根据@Ӫ_._ the对你问题的评论,我决定告诉你我编写代码的方式:

var robot = function( robotId )
{
  this.id = robotId;
  this.parts = [];
};
robot.prototype = {
  collectParts: function()
  {
    var robotInstance = this;

    $.getJSON(
      'some/url',
      function( json )
      {
        var i,
            responses = json.responses;
        for( i in responses )
        {
          if( Object.prototype.hasOwnProperty.call( responses, i ) )
          {
            robotInstance.parts = responses[i].parts;
          }
        }
      }
    );
  }
};
Run Code Online (Sandbox Code Playgroud)


Ral*_*nso 6

要访问thisjQuery函数内部,您需要将其分配给另一个变量,例如,self = this;然后替换thisself.