简体   繁体   中英

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

图像在这里

In chrome dev tools, if you click the unfold icon you can see the prototype properties in __proto__ :

截屏

You can see that getName() is defined there. That's the proper place for it since it's a property of the prototype, not the person object itself.

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM