注意:是的,有类似的问题,但我无法将集合传递给函数。将对象添加到扩展数组的JS集合(继承?)
$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/
请不要建议插件。我想创建我自己的对象收集器。
我的代码是怎么回事?
我做了一个小提琴...
如果我开始收集与function..it将工作以外的对象,所以这是一个继承的问题。这是怎么回事?
它是否给你一个错误的小提琴? – amanuel2
你有一些例子吗? –
你不能像这样扩展数组。 [你不能在ES5中扩展'Array'](http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/)。 – Bergi