注意:是的,有类似的问题,但我在将集合传递给函数时遇到了麻烦。
$j = jQuery.noConflict();
// objects.json shows: {"objects": ["hello", "hi", "yo"]}
function ObjectCollection() {
}
ObjectCollection.prototype = [];
ObjectCollection.prototype.fetch = function() {
var parent = this;
$j.getJSON("objects.json", function(data) {
$j.each(data.objects, function(i, customObject) {
var myCustomObject = new CustomObject(customObject);
parent.push(myCustomObject);
});
console.log(parent); // array exists
});
console.log(parent); // its gone!
};
function CustomObject(name) {
this.name = name;
}
function doSomethingWithCollection(objectCollection) {
this.objectCollection = objectCollection;
this.objectCollection.fetch();
console.log(this.objectCollection); // shows object collection with object in console
console.log(this.objectCollection.length); // equals 0?? should be 3!
this.objectCollection.forEach(function(object) {
// it wont iterate
console.log(object);
});
}
var collection = new ObjectCollection;
// if i uncomment the next two lines, the code will work
// var object = new CustomObject('myName');
// collection.push(object);
doSomethingWithCollection(collection);
编辑......好吧,我的问题是:https://jsfiddle.net/qd42fknL/
请不要建议插件。我想创建自己的对象收集器。
我的代码发生了什么?
我做了一个小提琴...
如果我使用函数外部的对象启动集合,它将起作用,因此这是一个继承问题。怎么回事?
答案 0 :(得分:0)
修改强>
我意识到问题根本不在于继承。这里的问题是你发送一个ajax请求,在它真正完成之前,你正在做console.log
。所以,这会产生错误的结果。
有两种解决方法可以解决这个问题。
这是一个使用异步ajax调用的工作解决方案。
$j = jQuery.noConflict();
function ObjectCollection() { }
ObjectCollection.prototype = [];
ObjectCollection.prototype.fetch = function(callback) {
var parent = this;
$j.getJSON("objects.json", function(data) {
$j.each(data.objects, function(i, customObject) {
var myCustomObject = new CustomObject(customObject);
parent.push(myCustomObject);
});
callback(); // notify request is completed
});
};
function CustomObject(name) {
this.name = name;
}
function doSomethingWithCollection(objectCollection) {
this.objectCollection = objectCollection;
var that = this;
this.objectCollection.fetch(function () {
// do this only after ajax finishes
console.log(that.objectCollection);
console.log(that.objectCollection.length);
that.objectCollection.forEach(function(object) {
console.log(object);
});
});
}
var collection = new ObjectCollection;
doSomethingWithCollection(collection);