Javascript 在JS中的所有类实例上执行方法
假设我有一个类,其方法如下:Javascript 在JS中的所有类实例上执行方法,javascript,class,oop,Javascript,Class,Oop,假设我有一个类,其方法如下: class MyClass { importantMethod() { ... //any code here } } 假设我有10/20/多个类的实例,比如: const inst1 = new MyClass(); const inst2 = new MyClass(); const inst3 = new MyClass(); .... //and more instances here 是否有一种方法可以在每个实例上以比以下更优雅的
class MyClass {
importantMethod() {
... //any code here
}
}
假设我有10/20/多个类的实例,比如:
const inst1 = new MyClass();
const inst2 = new MyClass();
const inst3 = new MyClass();
.... //and more instances here
是否有一种方法可以在每个实例上以比以下更优雅的方式执行importantMethod()
:
inst1.importantMethod()
inst2.importantMethod()
inst3.importantMethod()
.... //and for all the instances
我认为你有两个选择:
const实例=[];
对于(设i=0;i我认为您有两种选择:
如果这可以在初始化时运行,并且不会抛出错误等,并且是安全的,那么您可以在构造函数中运行它,因此每次有新实例时,它都会调用它…这不是最佳实践,但可能
做点像
const实例=[];
对于(设i=0;i使用
使用
我假设您希望能够在任何给定时刻碰巧存在的类的所有实例上运行函数(在任何时间,可能多次)。您可以通过模拟“私有静态”来实现这一点该类实例的列表。每个实例都会添加到该类的构造函数
调用的列表中,您可以提供一个函数来迭代该列表:
let MyClass;
{
// this is only visible to functions inside the block
let myClassInstances = [];
MyClass = class {
constructor() {
myClassInstances.push(this);
}
importantMethod() {
console.log(this);
}
}
MyClass.runImportantMethodOnAll = function() {
myClassInstances.forEach(inst=>inst.importantMethod());
}
};
您可以这样使用:
let x = new MyClass();
let y = new MyClass();
MyClass.runImportantMethodOnAll();
也不需要将runimportantMethodAll
附加到MyClass
。您可以将其存储在任何位置。我假设您希望能够在任何给定时刻对碰巧存在的类的所有实例运行函数(在任何时间,可能多次)。您可以通过模拟“私有静态”来实现这一点该类实例的列表。每个实例都会添加到该类的构造函数
调用的列表中,您可以提供一个函数来迭代该列表:
let MyClass;
{
// this is only visible to functions inside the block
let myClassInstances = [];
MyClass = class {
constructor() {
myClassInstances.push(this);
}
importantMethod() {
console.log(this);
}
}
MyClass.runImportantMethodOnAll = function() {
myClassInstances.forEach(inst=>inst.importantMethod());
}
};
您可以这样使用:
let x = new MyClass();
let y = new MyClass();
MyClass.runImportantMethodOnAll();
也不需要将runimportantMethodAll
附加到MyClass
。您可以将其存储在任何地方。它真的很棒!谢谢!真的很棒!谢谢!