我一直在寻找一种方法来获取在 Javascript 中实现特定原型(prototype)的所有对象。
我想要完成的是自动发现运行时可用的内容。我有一个基本原型(prototype),我们称之为“Widget”,我打算扩展它以制作各种类型的Widget。我发现了几个讨论如何实现 Java 风格的站点 Reflections API in JavaScript ,我计划使用它来动态地引入各种小部件的功能。我缺少的是能够说“给我所有 Widget
的东西”
对于展示和讲述部分,这就是我定义“小部件”的方式
Widget = function(document) {
if (document) {
this._type = document.type;
this._value = document.value;
}
};
Widget.prototype = {
get type() {
return this._type;
},
get value() {
return this._value;
},
set value(value) {
this._value = value;
},
get someCustomWidgetMethod() {
// Do something Widget-ish
}
};
以及 Widget 的扩展:
MyWidget = function(document) {
Widget.apply(this,arguments);
this.type = "MyWidget";
// Custom stuff here
};
MyWidget.prototype = Object.create(Widget.prototype, {
// MyWidget's prototype extensions
});
MyWidget.prototype.constructor = MyWidget;
最佳答案
类似的事情:
var ClassSystem = {
subClasses: [],
getByBaseClass: function (baseClass) {
return this.subClasses.filter(function (subClass) {
return (subClass.prototype instanceof baseClass);
});
},
extend: function (subClass, baseClass, config) {
subClass.prototype = Object.create(baseClass.prototype, config || {});
subClass.prototype.constructor = subClass;
this.subClasses.push(subClass);
return subClass;
}
};
用法:
// Base Class
function Widget() {}
Widget.prototype.sayHello = function () {
console.log('hello');
};
// Sub Class
function MyWidget() {}
// Inherit
ClassSystem.extend(MyWidget, Widget)
console.log(ClassSystem.getByBaseClass(Widget).length) // Will output 1
console.log(ClassSystem.getByBaseClass(Widget)) // Will output [MyWidget()]
只是一个非常简单的版本,您可以根据需要进行扩展。
关于javascript - 有没有办法在 JavaScript 中获取扩展原型(prototype)的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29748722/