A
A
Arkhan Milarov2020-08-02 06:12:11
Node.js
Arkhan Milarov, 2020-08-02 06:12:11

How to display the methods that an instance of a class has in the console in Node.js?

When in the console I output console.log(global); (this is an example, any object can be here), I only see this:

<ref *1> Object [global] {
  global: [Circular *1],
  clearInterval: [Function: clearInterval],
  clearTimeout: [Function: clearTimeout],
  setInterval: [Function: setInterval],
  setTimeout: [Function: setTimeout] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  },
  queueMicrotask: [Function: queueMicrotask],
  clearImmediate: [Function: clearImmediate],
  setImmediate: [Function: setImmediate] {
    [Symbol(nodejs.util.promisify.custom)]: [Function (anonymous)]
  }
}


I need the whole chain of prototypes of their properties and methods to be displayed in the console. How to do this with console in Node.js ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-08-02
@ArhanMilarov

First, log via console.dir with showHidden: true

// Для класса ClassName
console.dir(ClassName.prototype, {showHidden: true});

// Для любого объекта или инстанса класса obj
console.dir(Object.getPrototypeOf(obj), {showHidden: true});

Well, knowing that any prototype is also an object, and the root prototype is always null, you can just go recursively to see the whole chain:
class SomeClass extends Array {}
function collectPrototypesChain(obj) {
  const proto = Object.getPrototypeOf(obj);
  if(!proto) { return null; }
  const {name} = proto.constructor;
  return {name, proto, next: collectPrototypesChain(proto)};
}

console.dir(collectPrototypesChain(new SomeClass()), {showHidden: true, depth: 4});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question