Javascript Java脚本中构造函数和另一个函数之间的共享逻辑
我有这样的情况:Javascript Java脚本中构造函数和另一个函数之间的共享逻辑,javascript,Javascript,我有这样的情况: class TestClass { constructor() { shared logic } anotherFunction() { shared logic } } 如何在不复制代码的情况下实现这一点?将代码放入另一个函数(),然后从构造函数调用此函数 class TestClass { constructor() { this.anotherFunction(); } anotherFunction() {
class TestClass {
constructor() {
shared logic
}
anotherFunction() {
shared logic
}
}
如何在不复制代码的情况下实现这一点?将代码放入另一个函数(),然后从构造函数调用此函数
class TestClass {
constructor() {
this.anotherFunction();
}
anotherFunction() {
here is some logic to do
}
}
将代码放入另一个函数(),然后从构造函数调用此函数
class TestClass {
constructor() {
this.anotherFunction();
}
anotherFunction() {
here is some logic to do
}
}
一如既往,为共享逻辑创建一个函数,可以在类内部,也可以在类外部
class测试类{
构造函数(){
this.sharedLogicFunction();
}
另一个函数(){
this.sharedLogicFunction();
}
sharedLogicFunction(){}
}
一如既往,在类内部或外部为共享逻辑创建一个函数
class测试类{
构造函数(){
this.sharedLogicFunction();
}
另一个函数(){
this.sharedLogicFunction();
}
sharedLogicFunction(){}
}
嗯。。。将逻辑放在另一个函数中,并从构造函数调用它?嗯。。。将逻辑放在另一个函数中,并从构造函数调用它?这看起来完全正确!请注意,此处唯一的限制是在引用此之前必须调用super
。如果出于某种奇怪的原因,sharedLogicFunction
需要在调用super
之前发生,sharedLogicFunction
需要被设置为静态的,或者在类之外定义。但是,是否需要调用super才能访问父类,即当子类扩展父类时?然后我们就可以访问父方法。在上面的场景中,真的需要调用super来使用“this”吗?这看起来完全正确!请注意,此处唯一的限制是在引用此之前必须调用super
。如果出于某种奇怪的原因,sharedLogicFunction
需要在调用super
之前发生,sharedLogicFunction
需要被设置为静态的,或者在类之外定义。但是,是否需要调用super才能访问父类,即当子类扩展父类时?然后我们就可以访问父方法。在上面的场景中,真的需要调用super来使用“this”吗?