Javascript 创建实例时调用类中的所有方法
假设我有一个这样的类Javascript 创建实例时调用类中的所有方法,javascript,iife,Javascript,Iife,假设我有一个这样的类 class Foo { bar() { console.log('bar'); } baz() { console.log('baz'); } // other methods... } 我希望在创建新实例时无条件调用它的所有方法。我该怎么做呢 我目前正在通过调用类构造函数方法中的每个方法来实现这一点 class Foo { constructor() { this.bar(); this.baz();
class Foo {
bar() {
console.log('bar');
}
baz() {
console.log('baz');
}
// other methods...
}
我希望在创建新实例时无条件调用它的所有方法。我该怎么做呢
我目前正在通过调用类构造函数方法中的每个方法来实现这一点
class Foo {
constructor() {
this.bar();
this.baz();
// other methods
}
bar() {
console.log('bar');
}
baz() {
console.log('baz');
}
// other methods...
}
这里有一个片段
class-Foo{
构造函数(){
这个.bar();
这个.baz();
//其他方法
}
bar(){
console.log('bar');
}
baz(){
console.log('baz');
}
//其他方法。。。
}
新Foo()代码>如果调用方法的顺序不重要,则可以使用方法动态迭代所创建实例的属性:
可以通过以下方式声明函数:
bar = function() {
console.log('bar');
};
并迭代新实例的值,检查函数并调用它们:
class Foo {
constructor() {
Object.values(this).forEach(value => {
if (typeof value === 'function') {
value();
}
});
}
nonFunctionProp = 'nfp';
bar = function() {
console.log('bar');
};
baz = function() {
console.log('baz');
};
// other methods...
}
new Foo();
只需使用一个transpiler,例如,您发布的最后一个示例将在任何地方都可以使用(在IE11中成功测试)。如果iifes示例的属性在行为方面满足您的要求,那么它确实会让人质疑您为什么要首先使用类
class Foo {
constructor() {
Object.values(this).forEach(value => {
if (typeof value === 'function') {
value();
}
});
}
nonFunctionProp = 'nfp';
bar = function() {
console.log('bar');
};
baz = function() {
console.log('baz');
};
// other methods...
}
new Foo();