A
A
asker2018-10-26 14:01:44
JavaScript
asker, 2018-10-26 14:01:44

Is it legal to assign an instance to a class property?

If I need only one instance for the entire program, it is convenient to write this instance to a class property and then use its methods in the future. Is there any reason why you can't do that? Or is it better to create a new instance each time? For example, my class creates an element during initialization and inserts it into the markup, I only need to create this element once.

class A {
  constructor() {}

  methodA() {
    this.b.methodB();
  }

  init() {
    this.b = new B();
    this.methodA();
  }

}

class B {
  constructor() {}

  methodB() {
           console.log('methodB');
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-10-26
@bybyby

Yes, it's allowed.
Only this property of object instead of a class. When you did
foo = new A() // a new object was created, an instance of class A.
bar = new A() // another new object was created, an instance of class A.
// When you do
foo.init() // was created B, registered in the property of the foo object, but at the same time bar has nothing in this property, because it has not yet been init

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question