0

I'm looking for a way (preferably without constructing a container they are added to) to loop through all instances of a JavaScript pseudoclass without looping nesting the instances off and looping through all children recursively of the window object. Is this possible or do I have no recourse but to create an array holding all instances of any pseudoclass I want to access all the instances of?

4

2 に答える 2

0

次のコードでこれを解決することができました(そして、継承チェーンの継承ごとにオブジェクトのダミーインスタンスを作成する必要がなくなりました):

Object.defineProperty(Object.prototype, 'constructing', {
    enumerable: false,
    writable: true,
    value: false
});
Object.defineProperty(Object.prototype, 'construct', {
    enumerable: false,
    get: function () {
        if ((this === Object) || (this.constructor === Object)) { return; }
        if (this.constructing === false) {
            this.constructing = this.__proto__.constructor;
        }
        if (this.constructing.hasOwnProperty('instances')) { this.constructing.instances.push(this); }
        var c = this.constructing;
        if ('base' in c) {
            this.constructing = c.base;
            this.constructing.call(this);
        }
        if (c !== this.__proto__.constructor) {
            for (var i in c.prototype) {
                if (!this.__proto__.hasOwnProperty(i)) { this.__proto__[i] = c.prototype[i]; }
            }
        }
    }
});

function A() {
    this.construct;
    this.foo = 'foo';
}
function A_bar() { console.log(this.foo + 'foo'); }
A.prototype.constructor = A;
A.prototype.bar = A_bar;
A.instances = new Array();

function B() {
    this.construct;
    this.foo = 'bar';
    var base = this.__proto__.constructor.base.prototype;
}
function B_bar() { console.log('bar'); }
B.base = A;
B.prototype.constructor = B;
B.prototype.bar = B_bar;
B.instances = new Array();

document.write(A.instances.length);
document.write(B.instances.length);
var a = new A();
document.write(a.foo);
document.write(A.instances.length);
document.write(B.instances.length);
var b = new B();
document.write(b.foo);
document.write(A.instances.length);
document.write(B.instances.length);
var c = new B();
document.write(c.foo);
document.write(A.instances.length);
document.write(B.instances.length);
a.bar();
b.bar();
c.bar();

出力:

00foo10bar21bar32
于 2013-02-25T18:12:31.420 に答える
0

It's not possible, since the an object does not know what other objects inherit from it. It's a unidirectional relation (from object/instance to prototype).

And not all objects are reachable via recursing over window. You don't have access to local variables in functions.

You have to keep track of created instances manually.

于 2013-02-25T11:51:27.573 に答える