简体   繁体   中英

Is bad practice to create instance of class in constructor with new keyword?

I have class in Javascript and need one object in this class from other class. My question is which is better ?

create instance of class out of class definition or create in constructor ?

sample code:

const b = new B();

class A {
  // and then use b
}
// or 
class A {
 constructor() {
 const b = new B();
 }
}

Whichever class controls the lifetime of the other object(s) creates those objects.

In your example, if A controls the lifetime of that particular instance of B , then it is fine to create B in the constructor.

However, if another class controls the lifetime of (or owns) the object from B , then an instance of B should be passed to A in the constructor.

The test is simple: the class that is responsible for the lifetime of other objects is responsible for creating those objects.

If they are both classes can you just extend the class you need.

class b {}

class a extends b {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM