Get all instances of class in Javascript

前端 未结 5 832
再見小時候
再見小時候 2020-12-03 12:19

I thought there would already be an answer for this but I can\'t seem to find one.. How can I run a particular class method on all instances of this class in Javascript?

5条回答
  •  长情又很酷
    2020-12-03 12:40

    You'll have to provide a custom implementation.

    I would do something like this :

    function Class() {
        Class.instances.push(this);
    };
    Class.prototype.destroy = function () {
        var i = 0;
        while (Class.instances[i] !== this) { i++; }
        Class.instances.splice(i, 1);
    };
    Class.instances = [];
    
    var c = new Class();
    Class.instances.length; // 1
    c.destroy();
    Class.instances.length; // 0
    

    Or like this :

    function Class() {};
    Class.instances = [];
    Class.create = function () {
        var inst = new this();
        this.instances.push(inst);
        return inst;
    };
    Class.destroy = function (inst) {
        var i = 0;
        while (Class.instances[i] !== inst) { i++; }
        Class.instances.splice(i, 1);
    };
    
    var c = Class.create();
    Class.instances.length; // 1
    Class.destroy(c);
    Class.instances.length; // 0
    

    Then you could loop through all instances like so :

    Class.each = function (fn) {
        var i = 0, 
            l = this.instances.length;
        for (; i < l; i++) {
            if (fn(this.instances[i], i) === false) { break; }
        }
    };
    
    Class.each(function (instance, i) {
        // do something with this instance
        // return false to break the loop
    });
    

提交回复
热议问题