在Javascript中通过原型访问Date对象的方法

时间:2013-10-04 21:49:49

标签: javascript function class methods prototype

我试图通过使用getTime对象的原型继承/获取对Date对象的所有属性/方法的访问权限,但我遗漏了一些东西。请指出正确的方向。

//empty constructor 
function getTime(){}

//attempt to inherit all of the properties and methods of Date object
getTime.prototype = new Date();

//create a new Date object and test
//this works
var wt = new Date();
alert(wt);

//create a new getTime object and test.
//I was uner the impression that getTime object 
//now has access to all the properties/methods of the Date object.
//'This generates:TypeError this is not a Date object.'
var wt2 = new getTime();
alert(wt2.getHours());

JSfiddle:http://jsfiddle.net/nysteve/QHumL/12/

2 个答案:

答案 0 :(得分:1)

访问Date对象的原型实际上正在工作,但这些方法希望处理Date类型的对象。更多详情:https://stackoverflow.com/a/7141488/2847629

答案 1 :(得分:0)

我认为你的getTime构造的对象 可以访问Date对象的所有属性/方法。如果没有,则错误类似于getHours is not a function(因为它将是未定义的)。

我不确定如何实现Date对象的getHours方法,但JavaScript确实有hasOwnProperty方法。如果Date对象是您在JavaScript中实现的,那么您可以编写其getHours方法来检查它被调用的对象(在您的示例中为wt2)是否已定义属性本身(而不是原型对象)。

Date对象的getHours方法可能正在做类似的事情。

相关问题