简体   繁体   中英

Javascript user defined prototypes returned with object on console

In JavaScript I noticed that my console.log prints the object plus any user-defined prototypes.

Date.prototype.getWeekNumber = function() {
}

Date.prototype.addDay = function() {
}

a = new Date();

console.log(a);
console.log("a - " + a);

Outputs:

[object Date] {
  addDay: function() {
},
  getWeekNumber: function() {
}
}
"a - Mon Jun 03 2019 13:58:05 GMT-0400 (Eastern Daylight Time)"

Converting console.log output to a string renders values as expected, but if you just console the object, is there anything that can be done to declutter the console so that only the objects are printed for debugging purposes and the user-defined prototypes are not expanded like the following output when the user-defined prototypes are removed from the code?

[object Date] { ... }
"a - Mon Jun 03 2019 14:01:00 GMT-0400 (Eastern Daylight Time)"

Not a big deal, but I could not find a similar question so I thought I would ask. Thanks in advance.

Do you mean to just log the date as String?

console.log(a.toString());  

Or if that's too many keystrokes:

console.log(""+a);

Properties are enumerable by default. This means they are considered important to list when examining the properties of the object.

You can use Object.defineProperty with the enumerable: false to create a property that is not enumerable. It's still there, but it will not be listed when asked to display all its properties.

 // Properties are enumerable by default. Date.prototype.enumerable = function() { return 'enumerable'; }; // Use Object.defineProperty to create a non non enumerable property Object.defineProperty(Date.prototype, 'nonEnumerable', { enumerable: false, configurable: false, writable: false, value: function() { return 'nonEnumerable'; // logic todo... } }); a = new Date(); // Iterate over all enumerable keys for (const key in a) { console.log('enumerable key: ' + key); // only 'enumerable' is logged } // But both properties are present console.log(a.enumerable()) //-> 'enumerable' console.log(a.nonEnumerable()) //-> 'nonEnumerable' 

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