向扩展数组的JS集合添加对象(继承?)

Adding object to JS collection that extends the array (inheritance?)

本文关键字:对象 继承 添加 集合 扩展 数组 JS      更新时间:2023-09-26

注意:是的,也有类似的问题,但我在将集合传递到函数中时遇到了问题。

$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。因此,这会产生错误的结果。

有两种解决方案可以克服这一问题。

  1. 使用同步ajax请求(但不建议这样做)
  2. 等待异步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/