Note: Yes there are similar questions but I'm having trouble passing the collection into a function.
$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);
Edit... ok, my problem is this: https://jsfiddle.net/qd42fknL/
Please don't suggest plugins. I want to create my own object collector.
What's going on with my code?
I made a fiddle...
If I initiate the collection with an object outside of the function..it will work, so this is an inheritance problem. Whats going on?