日期原型属性

Date prototype property

本文关键字:属性 原型 日期      更新时间:2023-09-26

当我深入到Javascript中时,我在尝试测试时得到了这个奇怪的结果。

function CustomeObject() {
    this.type = "custom";
};
var node1 = document.createTextNode(Date.prototype);
var node2 = document.createTextNode(CustomeObject.prototype);
document.getElementsByTagName("body")[0].appendChild(node1);
document.getElementsByTagName("body")[0].appendChild(node2);

结果如下:

无效日期[object object]

正如我从互联网上的一个来源读到的那样:原型是任何对象的内置属性,它实际上是一个对象本身。但是这个测试在Date对象上失败了。你能告诉我测试Date原型属性的代码出了什么问题吗?非常感谢。

Date.prototype传递给document.createTextNode()时,它将在传递的对象上隐式调用toString()

toString()的默认输出是[object Object],如您的第二个测试所示。

然而,Date.prototype有自己的toString()函数,其目的是将当前Date对象(即this)作为文本返回。

var now = new Date();
console.log(now.toString()); // outputs current date
console.log(now);            // does the same due to implicit toString() call

当您直接调用该函数时,其this指针错误地包含Data.prototype而不是日期对象,因此"Invalid Date"输出。

因为Date.prototype是其.toString()返回Invalid Date的对象。

var d = Date.prototype;
console.log(d); // will output 'Invalid Date', because the object doesn't have any date info.
d.setFullYear(2012);
console.log(d); // will output the date string.