簡體   English   中英

通過Javascript中的原型訪問Date對象的方法

[英]Accessing Date object's methods via prototype in Javascript

我試圖通過使用我的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/

實際上,可以訪問Date對象的原型,但是這些方法希望處理Date類型的對象。 此處有更多詳細信息: https : //stackoverflow.com/a/7141488/2847629

我認為您的getTime構造對象確實可以訪問Date對象的所有屬性/方法。 如果不是,則錯誤將類似於getHours is not a function (因為它將是未定義的)。

我不確定如何實現Date對象的getHours方法,但是JavaScript確實具有hasOwnProperty方法。 如果Date對象是用JavaScript實現的,則可以編寫其getHours方法來檢查其調用的對象(在您的示例中為wt2 )是否具有在其自身(而不是其原型)上定義的屬性。賓語)。

Date對象的getHours方法可能正在執行類似的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM