Search code examples
javascriptconsole.logfunction-constructor

console.log() an object does not log the method added via prototype in node js console. Or how to print the prototypes also?


function Person(name)  {
        this.name = name;
    }

    Person.prototype.getName = function() {
        return this.name
    }

    var tinu = new Person('Tinu');

    console.log(tinu.getName()) //Prints the name 'Tinu' - Expected, means the function is added to protoype

    console.log(tinu);

The last console.log() does not print the newly added method named 'getName' via dot prototype, prints only the property 'name', Here I would expect to print both property 'name' and also method 'getName' inside the Person object. Below is the actual output and desired output for the above code:

Actual output

Tinu
Person { name: 'Tinu' }

Desired output

Tinu
Person { name: 'Tinu', getName: [Function] }

The image below shows another example where the method 'getFullName' added via prototype is correctly shown while printing to console the object to which it is added. And was expecting the same with my example

image here


Solution

  • console.log is a provided API by your js-environment (in your case Node.js). There's no standard spec. So in your case console.log prints a simple string representation of your Javascript-object.

    { propName: propValue }
    

    In Node.js there's a util-module (util-documentation). Furthermore I found a method, which returns all properties of an object including all properties of the prototype-chain.

    const util = require('util')
    
    function Person(name)  {
        this.name = name;
    }
    
    Person.prototype.getName = function() {
        return this.name
    }
    
    var tinu = new Person('Tinu');
    
    console.log(util.inspect(tinu, {showHidden: false, depth: null}))
    
    function getAllPropertyNames(obj) {
      var props = [];
    
      do {
        Object.getOwnPropertyNames(obj).forEach(function (prop) {
          if (props.indexOf(prop) === -1 ) {
            props.push( prop );
          }
        });
      } while (obj = Object.getPrototypeOf(obj));
    
      return props;
    }
    
    console.log(getAllPropertyNames(tinu)); 
    /*
    [ 'name',
      'constructor',
      'getName',
      '__defineGetter__',
      '__defineSetter__',
      'hasOwnProperty',
      '__lookupGetter__',
      '__lookupSetter__',
      'isPrototypeOf',
      'propertyIsEnumerable',
      'toString',
      'valueOf',
      '__proto__',
      'toLocaleString' ]
     */
    

    If you are on a Browser and want to see defined methods and other infos, you can use your browser's developer tools. Press F12 and you can do a lot of investigation.

    enter image description here