[英]variable scope in nest object function of javascript and jQuery
我写了两个对象。 一个叫做List,另一个叫做Car。
function Car()
{
this.make="";
this.year="";
}
function List()
{
this.cars = [];
}
我还有另一个功能,它是对象List的一种方法,用于读取XML文件的信息,并将其存储在List对象内部的car数组中:
List.prototype.readXML = function()
{
var i = 0;
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(){
//Bug Point!!!
this.cars.push(new Car()); //Push a Car object into array
this.cars[i].ID = ($(this).attr("ID"));
});
});
}
但是,这行不通。 每次调试时,我都没有定义汽车...我尝试使用var代替它来定义汽车。 并尝试删除this.cars.push而不是cars.push。 但是仍然说没有定义汽车。
我假设在这个问题中变量范围可能会出问题。 有人可以教我怎么做吗?
谢谢!
问题出在每个jQuery
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(){
//Bug Point!!!
this.cars.push(new Car()); //Push a Car object into array
this.cars[i].ID = ($(this).attr("ID"));
});
});
this
与您期望的内容无关
解决此问题的一种常用方法是将其分配给另一个变量that
变量称为that
或self
List.prototype.readXML = function()
{
var i = 0;
// Create a new variable called 'self' that you can refer to within different function scopes
var self = this;
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(){
self.cars.push(new Car()); //Push a Car object into array
self.cars[i].ID = ($(this).attr("ID"));
});
});
}
这意味着您可以访问需要访问的原始List对象。 此方法利用了闭包的优势。
希望这可以帮助
编辑评论中提出的解释性问题:
List.prototype.readXML = function()
{
// Create a new variable called 'self' that you can refer to within different function scopes
var self = this;
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(i, domElem){
var car = new Car();
car.id = $(domElem).attr("ID");
self.cars.push(car); //Push a Car object into array
});
});
}
您遇到的问题与闭包有关。
基本上,此范围在.each语句内更改。 .each不再引用List,它引用XML内部的当前“项目”。
要解决此问题,请参阅JavaScript闭包如何工作?
List.prototype.readXML = function()
{
var i = 0;
var self = this;
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(){
//Bug Point!!!
self.cars.push(new Car()); //Push a Car object into array
self.cars[i].ID = ($(this).attr("ID"));
});
});
}
问题在于, 此上下文随Ajax回调而改变。 我会在原型上定义一个addCar方法,并使用它来添加新汽车。 像这样:
List.prototype.addCar = function(data) {
this.cars.push(new Car()); //Push a Car object into array
this.cars[i].ID = ($(data).attr("ID"));
}
List.prototype.readXML = function()
{
var i = 0;
var self = this;
$.get('mydata.xml', function(xml){
$(xml).find("item").each(function(){ self.addCar(this); });
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.