您可以编写一个简单的通用实例化/继承助手,它在数组中跟踪其实例
像这样的事情可能会做到
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的例子