查找扩展基类的Javascript应用程序中的所有类 [英] Find all classes in a Javascript application that extend a base class

查看:81
本文介绍了查找扩展基类的Javascript应用程序中的所有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码

class Animal{}
class Dog extends Animal {}
class Cat extends Animal {}
class Donkey extends Animal {}

我想看看我的应用程序的Universe中的所有类,当我找到一个来自Animal的类时,我想创建一个该类型的新对象并将其添加到列表中。这允许我添加功能而无需更新事物列表。所以我可以避免以下情况:

I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list. This allows me to add functionality without having to update a list of things. So I can avoid the following:

var animals = [];
animals.push( new Dog() );
animals.push( new Cat() );
animals.push( new Donkey() );

PS:我不想在我的类中添加额外的功能或明确地调用它们。

PS: I don't want to add extra functionality to my classes or call them explicitly.

推荐答案

这是我到目前为止所发现的
http://jsbin.com/xiroyurinu/1/edit?js,console,output

Here what I discovered so far http://jsbin.com/xiroyurinu/1/edit?js,console,output

class Animal{}
class Dog extends Animal {}
class Cat extends Animal {}
class Donkey extends Animal {}

var animals = getAllSubclasses(Animal);

console.log(animals.map(function(c){ return new window[c] })) // creates objects
document.body.innerText = animals; // Dog, Cat, Donkey

和魔法

function getAllSubclasses(baseClass) {
  var globalObject = Function('return this')(); 
  var allVars = Object.keys(globalObject);
  var classes = allVars.filter(function (key) {
  try {
    var obj = globalObject[key];
        return obj.prototype instanceof baseClass;
    } catch (e) {
        return false;
    }
  });
  return classes;
}

这种方法的主要缺点是我无法使用ES6模块导入和必须做旧式和简单的文件连接,但这仍然更好,没有。

The main disadvantage of this method is that I can not use ES6 module import and have to do old fashioned and simple contatenation of files, but this is still better that nothing.

PS:仍在等待更好的答案

PS: still wait for better answer

UPD:我知道要使用这个必须全局定义所有类,这就是为什么我寻找更好的方法来做到这一点..

UPD: and ye, i know that to use this all classes must be defined globally, that's why i search for better way to do this..

这篇关于查找扩展基类的Javascript应用程序中的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆