注意:是的,有類似的問題,但我無法將集合傳遞給函數。將對象添加到擴展數組的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