Example: how to check that variable a is an instance of class B?
let A = function() { class B { } return B; } let a = new A(); Example: how to check that variable a is an instance of class B?
let A = function() { class B { } return B; } let a = new A(); 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 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). - user207618q 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 pmI 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); Source: https://ru.stackoverflow.com/questions/516522/
All Articles
instanceof()method can help. - Sergiks