日期原型属性
Date prototype property
当我深入到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.
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 附加到原型属性的Do函数没有闭包
- 日期原型属性
- 价值、原型和属性的差异
- 使用闭包创建原型中引用的私有属性
- 为什么属性存在于对象实例上,即使其原型发生了更改
- 为什么在原型中定义属性被视为反模式
- JS构造函数的原型属性与其原型之间的区别
- 为什么函数对象的实例没有继承函数原型属性
- 组件是HTML5的属性还是原型.js的东西
- 为什么浏览器显示原型属性不同
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- Javascript设置&阴影属性(原型链)
- 高图表热图 未捕获类型错误:无法读取未定义的属性“原型”
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 未捕获的类型错误:无法读取未定义的属性“原型”
- 如何在DOM object的构造函数中添加属性.原型在Internet Explorer<=IE8
- 扩展类不能读取未定义的属性原型
- 未捕获的类型错误:无法读取未定义的 sails.io.js 的属性“原型”
- 升级到量角器4后无法读取未定义的属性“原型”