简体   繁体   English

Javascript用户定义的原型与控制台上的对象一起返回

[英]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. 在JavaScript中,我注意到我的console.log打印该对象以及任何用户定义的原型。

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? 将console.log输出转换为字符串将按预期方式呈现值,但是,如果您只是控制台对象,则可以做一些事情来整理控制台,以便仅打印对象以用于调试目的,而不会定义用户定义的原型从代码中删除用户定义的原型后,是否像下面的输出一样扩展?

[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? 您是说只将日期记录为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. 可以将Object.definePropertyenumerable: false一起使用以创建不可枚举的属性。 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' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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