![](/img/trans.png)
[英]How do you iterate over all methods in a JavaScript pseudoclass, regardless of whether or not they are marked enumerable?
[英]Is it possible to iterate over all instances of a JavaScript pseudoclass?
我正在尋找一種方法(最好是不構造將它們添加到的容器)循環遍歷JavaScript偽類的所有實例,而不循環嵌套實例並遞歸遍歷window對象的所有子級。 這是否可行,或者除了創建要保存要訪問其所有實例的任何偽類的所有實例的數組之外,我是否無權求助?
這是不可能的,因為一個對象不知道還有其他對象從該對象繼承。 這是一個單向關系(從對象/實例到原型)。
並非所有對象都可以通過在window
上遞歸來訪問。 您無權訪問函數中的局部變量。
您必須手動跟蹤創建的實例。
設法使用以下代碼解決了這個問題(並且無需為繼承鏈中的每個繼承創建對象的虛擬實例):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.