Home > Enterprise >  Why do simple objects not log consistently in different environments?
Why do simple objects not log consistently in different environments?

Time:06-13

It would really help debugging if all environments just logged the same content consistently! I am having a problem being able to just log the correct contents across different IDEs and browsers.

After reading various other posts (e.g. enter image description here

However, paste the same code into Safari’s JS console and the important part incorrectly logs as just User {}, not showing the object’s methods:

enter image description here

Additionally the CodePen’s important part just logs [object Object] {}:

enter image description here

And VSCode just logs {}.

So my question is how can you correctly log the methods of an object in all environments? It’s causing a nightmare trying to debug anything as some node code I have only runs in an IDE, unavailable to a browser.

This has come from a bug where I’m fetching an object from a mongo database that strangely doesn’t seem to have any methods despite the object having methods before being inserted into the database.

Any advice or debugging tips would be greatly appreciated, thank you.

CodePudding user response:

How different environments log an object is Image of VSCode debugger menu showing the joe object expanded on the left local variables panel showing the prototype methods, fn and fn2

class User {
  constructor(name) {
    this.name = name;
  }
  
  fn() {
    return 'fn';
  }
  
  fn2() {
    return 'fn2';
  }
  
  static staticFn() {
    return 'static fn'
  }
}

const joe = new User('Joe')
const getMethods = (obj) => {
  let curr = obj;
  while(curr !== Object.prototype) {
    const names = Object.getOwnPropertyNames(curr);
    for(const key of names)
      if(typeof curr[key] === "function")
        console.log(key, curr[key]);
    
    curr = Object.getPrototypeOf(curr);
  }
}

getMethods(joe);

  • Related