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;
}
});
}
}
我实际上如何分配 this.parts?
最佳答案
将对 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;
}
});
}
}
编辑: 我昨晚写了这个修改,然后决定不发布它。但是根据@Ӫ_._Ӫ 对您的问题的评论,我决定向您展示我编写代码的方式:
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;
}
}
}
);
}
};
关于Javascript对象和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7844416/