向扩展数组的JS集合添加对象(继承?)
Adding object to JS collection that extends the array (inheritance?)
注意:是的,也有类似的问题,但我在将集合传递到函数中时遇到了问题。
$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/
请不要建议使用插件。我想创建自己的对象收集器。
我的代码怎么了?
我做了一把小提琴。。。
如果我使用函数之外的对象启动集合。。它会起作用,所以这是一个继承问题。发生了什么事?
编辑
我意识到这个问题根本与继承无关。这里的问题是,您正在发送一个ajax请求,在它真正完成之前,您正在执行console.log
。因此,这会产生错误的结果。
有两种解决方案可以克服这一问题。
- 使用同步ajax请求(但不建议这样做)
- 等待异步ajax请求首先完成
下面是一个使用异步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);
这是小提琴https://jsfiddle.net/qd42fknL/2/
相关文章:
- JavaScript对象继承问题
- 我的Javascript对象继承自什么
- javascript对象继承-子类和超类
- 向扩展数组的JS集合添加对象(继承?)
- 使 HTML 元素从自定义对象继承事件
- 如何从“构造函数返回另一个对象”对象继承
- 在 Ember.js 中,如何使用 super() 遍历对象继承树
- 如何实现 JavaScript 对象继承
- Javascript 对象继承
- 使用jquery的函数对象继承's延伸
- 是否可以从javascript函数对象继承
- 从数组中的对象继承/调用函数
- 如何强制javascript数组从我的自定义对象继承
- 为什么不't我的对象继承了keys函数
- JavaScript中的对象继承
- 通过clone()实现对象继承是如何工作的
- 原型继承为什么子对象不从父对象继承方法
- 从Error对象继承-其中是消息属性
- JavaScript对象继承问题
- 对象继承