Javascript 对象和 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;
}
});
}
}
我如何实际分配 this.parts ?
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;
}
});
}
}
How do I actually assign this.parts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将对
this
的引用(当它在适当的范围内时)分配给变量,并在更改了this
范围的函数中使用该变量。在下面代码的修改版本中,robotInstance
是我选择使用的变量:编辑: 我昨晚编写了此修改,然后决定不发布它。但根据@֪_._֪对你的问题的评论,我决定向你展示我编写代码的方式:
Assign a reference to
this
(when it's in the proper scope) to a variable and use that variable in the function which has changed the scope ofthis
. In the modified version of your code below,robotInstance
is the variable I've opted to use:Edit: I had written this modification last night, then decided not to post it. But based on the comment to your question by @Ӫ_._Ӫ, I decided I'd show you the way I would write your code:
要在 jQuery 函数中访问
this
,您需要将其分配给另一个变量,例如self = this;
,然后将this
替换为自我。
To access
this
inside jQuery functions, you need to assign it to another variable, for instance,self = this;
then replacethis
withself
.您可以在“that”变量中捕获“this”,以便可以在 $.getJSON 的回调范围内使用它
You can capture "this" in a "that" variable so that it can be used inside the scope of the callback of your $.getJSON
只需将其分配给另一个变量即可,例如
Just assign this to another variable e.g that