【发布时间】:2016-09-20 09:06:03
【问题描述】:
考虑一下 JavaScript 的 Date 构造函数如何创建一个在直接引用时返回默认字符串的对象:
var date = new Date();
document.write(date); // Outputs string: Mon May 23 2016 08:48:14 GMT-0400 (EDT)
// Expected output: [object Object]
document.write('<br/>', date.getFullYear()); // Can call methods as expected.
document.write('<br/>', date.toString());
根据 MDN 文档:
如果没有提供参数,则构造函数会根据系统设置为当前日期和时间创建一个 JavaScript Date 对象。
(强调我的)
Date 构造函数返回一个对象,但是当直接引用该对象时,它返回一个表示当前日期和时间的字符串,而不是像预期的那样表示方法和属性。
如何使用自己创建的对象构造函数实现相同的行为?
例如:
// My CoolObj constructor function
var CoolObj = function () {
var self = this;
var i = 0;
this.coolMethod = function () {
i += 1;
return self.coolProperty + ' and increment ' + i;
};
this.coolProperty = 'My cool string';
}
var myCoolObj = new CoolObj(); // Instantiate new object from constructor;
// Just like `var date = new Date();` above.
document.write(myCoolObj); // Outputs [object Object];
// I want to output a string, like Date does.
// For example: 'My cool direct-reference string.'
document.write('<br/>', myCoolObj.coolProperty); // Can call properties...
document.write('<br/>', myCoolObj.coolMethod()); // ...and methods as expected.
我希望它在直接引用时返回某种字符串,同时提供正常调用其方法和属性的能力。
更新:
链接的问题确实提供了答案:
Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?
tl;dr: 定义 CoolObj.prototype.toString,它将被 console.log 和 document.write 等尝试cast的函数调用在输出之前将对象转换为字符串。
// My CoolObj constructor function
var CoolObj = function () {
var self = this;
var i = 0;
this.coolMethod = function () {
i += 1;
return self.coolProperty + ' and increment ' + i;
};
this.coolProperty = 'My cool string';
}
// Define a custom `toString` method on the constructor prototype
CoolObj.prototype.toString = function () {
return 'My cool direct-reference string.';
}
var myCoolObj = new CoolObj(); // Instantiate new object from constructor;
// Just like `var date = new Date();` above.
document.write(myCoolObj); // Outputs [object Object];
// I want to output a string, like Date does.
// For example: 'My cool direct-reference string.'
document.write('<br/>', myCoolObj.coolProperty); // Can call properties...
document.write('<br/>', myCoolObj.coolMethod()); // ...and methods as expected.
【问题讨论】:
-
@mdickin 我不是在寻求在控制台中为对象指定格式的帮助。我正在寻找如何为构造函数实例化的对象添加默认返回语句。
-
@gfullam
new Date()不返回字符串,而是返回一个对象。在其上调用console.log()会调用Date.toString()方法。运行typeof new Date()返回“对象” -
@mdickin 我知道
new Date()返回一个对象,这就是为什么我引用了 MDN 文档中的说明。正是这一事实让我质疑 Date 在直接引用时返回字符串的独特行为。我已经修改了我的示例,将其与console.log的用法分开,以展示我在我想用我自己构造的对象复制的日期构造对象中观察到的内容。 -
@bfmags 这是一个有趣的问题,只与我的问题无关,但它的答案很老套,并引入了严重的性能影响。我正在为我的问题寻找一种公认的“最佳实践”解决方案。
标签: javascript date