Example: how to check that variable a is an instance of class B?

let A = function() { class B { } return B; } let a = new A(); 

2 answers 2

To check the "relationship" you need to use instanceof . Although this method has some nuances .
In this case, everything is confused - A is created, which returns B , which is re-created in the closure and is not available externally. It turns out a not a descendant of A , since A returns B
Although it may seem that it is worth doing so:

 let a = new A, b = A(); // Создаём объект B и получаем ссылку на класс console.info(a instanceof b); // true 

But this will not work, because every time A is called, a new class B is created and destroyed when A is exited (there are no references to the class outside the function; the builder will remove it). Different objects are returned, albeit with the same name.

This is how you can do it:

 class B{} // Вытаскиваем из замыкания let A = function(){ return B; }; // Сначала создаём A, потом B let a = new (new A); console.info(a instanceof B); // true 

  • class B {f () {q = 2} ff () {console.log (q);}} let A = function () {let q = 1; return B; }; let a = new (new A ()); console.info (a instanceof B); Such a code, for some reason, is not executed, that is, B in this case does not see variables inside A - Yuri
  • @Yuri, q established and destroyed in A Nowhere is it indicated that it is referred to. Yes, the class method uses a variable named q , but it is not the same variable. From the point of view of the interpreter (and mine, by the way). - user207618
  • But then the meaning of such a construction as in the question is lost, because it was that instances of class B could see the internal variables of the function A - Yuri
  • @Yuri, the garbage collector keeps track of links; if there are no links to something, it is removed from memory. In your example, put q and ... return . That is, the collector sees that the variable is initialized and an exit has occurred. q (this is the one) is not used anywhere, it means it should be removed. q in a class is a completely different variable, which, by the way, no one has set in the method, and that’s a mistake. - user207618 4:05 pm
  • But how to still do so that he did not delete it? - Yuri

I don’t know how to construct a class description inside a function, but generally you can do this:

 class B { } let a = new B(); console.log(a instanceof B);