[英]Javascript user defined prototypes returned with object on console
在JavaScript中,我注意到我的console.log打印该对象以及任何用户定义的原型。
Date.prototype.getWeekNumber = function() {
}
Date.prototype.addDay = function() {
}
a = new Date();
console.log(a);
console.log("a - " + a);
输出:
[object Date] {
addDay: function() {
},
getWeekNumber: function() {
}
}
"a - Mon Jun 03 2019 13:58:05 GMT-0400 (Eastern Daylight Time)"
将console.log输出转换为字符串将按预期方式呈现值,但是,如果您只是控制台对象,则可以做一些事情来整理控制台,以便仅打印对象以用于调试目的,而不会定义用户定义的原型从代码中删除用户定义的原型后,是否像下面的输出一样扩展?
[object Date] { ... }
"a - Mon Jun 03 2019 14:01:00 GMT-0400 (Eastern Daylight Time)"
没什么大不了的,但是我找不到类似的问题,所以我想问一下。 提前致谢。
您是说只将日期记录为String吗?
console.log(a.toString());
或者,如果击键太多:
console.log(""+a);
默认情况下,属性是可枚举的。 这意味着在检查对象的属性时,将其列为重要对象。
可以将Object.defineProperty
与enumerable: false
一起使用以创建不可枚举的属性。 它仍然存在,但是在要求显示其所有属性时不会列出。
// 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.