配列内のインスタンスを追跡する単純な汎用インスタンス化/継承ヘルパーを作成できます
このような何かがそれを行うかもしれません
var base = (function baseConstructor() {
var obj = {
create:function instantiation() {
if(this != base) {
var instance = Object.create(this.pub);
this.init.apply(instance,arguments);
this.instances.push(instance);
return instance;
} else {
throw new Error("You can't create instances of base");
}
},
inherit:function inheritation() {
var sub = Object.create(this);
sub.pub = Object.create(this.pub);
sub.sup = this;
return sub;
},
initclosure:function initiation() {},
instances: [],
pub: {}
};
Object.defineProperty(obj,"init",{
set:function (fn) {
if (typeof fn != "function")
throw new Error("init has to be a function");
if (!this.hasOwnProperty("initclosure"))
this.initclosure = fn;
},
get:function () {
var that = this;
//console.log(that)
return function() {
if(that.pub.isPrototypeOf(this)) //!(obj.isPrototypeOf(this) || that == this))
that.initclosure.apply(this,arguments);
else
throw new Error("init can't be called directly");
};
}
});
Object.defineProperty(obj,"create",{configurable:false,writable:false});
Object.defineProperty(obj,"inherit",{configurable:false,writable:false});
return obj;
})();
var Student = base.inherit()
Student.init = function (age) {
this.age = age;
}
var student1 = Student.create(21)
var student2 = Student.create(19)
var student3 = Student.create(24)
console.log(Student.instances.length) // 3
JSBinの例を次に示します。