继承对象.遍历所有对象

Inherit objects. Iterate through all objects

本文关键字:对象 遍历 继承      更新时间:2023-10-25

这是我的问题:

我有一个继承对象(类)函数,我用x个多对象填充它,如下所示:

function Booking (doc_id, arrival_date, supplier_amount, client_amount, currency, profit, calculated_profit, currency_rate) {
    this.doc_id = doc_id;
    this.arrival_date = arrival_date;
    this.supplier_amount = supplier_amount;
    this.client_amount = client_amount;
    this.currency = currency;
    this.profit = profit;
    this.calculated_profit = calculated_profit;
    this.exchange_rate = currency_rate;
    if(pastDate(this.arrival_date)) {
        past_date: true;
    }
    else {
        past_date: false;
    }
} 

是否可以遍历所有对象?我想要一个函数来遍历所有Booking对象,并使用结果来填充dataTables表。我想这个函数必须由定义

Booking.prototype = { }

我在网上似乎找不到关于这件事的任何信息。我尝试了所有的想法都没有成功。

要迭代所有Booking实例,必须将对它们的引用存储在某个位置:

var Booking = (function() {
    var instances = []; // Array of instances
    function Booking(foo) {
        if (!(this instanceof Booking)) return; // Called without `new`
        instances.push(this); // Store the instance
        this.foo = foo; // Your current code
    }
    Booking.prototype.whatever = function() {
        // You can use `instances` here
    }
    return Booking;
})();

但请等待:不要这样做(除非绝对必要)。

上面的代码有一个大问题:由于Booking实例在instances中被引用,所以垃圾收集器不会杀死它们,即使它们在其他地方没有被引用。

因此,每次创建实例时,都会产生内存泄漏

ECMAScript 6引入了WeakSet,它允许您将弱持有对象存储在集合中,这样,如果它们没有在其他地方被引用,垃圾收集器就会杀死它们。但是WeakSet是不可迭代的,所以它们在您的情况下没有用处。