簡體   English   中英

向js對象的原型添加方法

[英]Add a method to prototype of js object

嘗試向js Date對象添加方法以獲取格式化日期,未在任何地方聲明Date或未使用new / create()調用Date

Date.prototype.format = function () {
       // return this.getFullYear() + '-' + ('0' + (this.getMonth() + 1)).slice(-2) + '-' + ('0' + this.getDate()).slice(-2)
       var curr_date = this.getDate();

    var curr_month = this.getMonth() + 1;

    var curr_year = this.getFullYear();

    return curr_year + "-" + curr_month + "-" + curr_date;
    }

我搞砸了this變量。 getDate()getMonth()getFullYear()Date對象的方法。

.getDate();時引發錯誤.getDate(); 稱為: undefined is not a function

請說明如何在原型中使用其他單一對象類型的方法。

如果您要使用它而不創建日期的新實例...呵呵

你可以做

 var d = new Date 

在功能上。 並將所有內容替換為d。 那你可以做

Date.prototype.format()

但是,如果您仍然想要這個,那就做吧

new Date().format()

您是否有可能將此稱為屬性而不是方法? 我只是將您的代碼放入Chrome的控制台中,通過將其作為一種方法調用,它似乎可以正常工作。

new Date().format; // does not work

new Date().format(); // works

如果仍然遇到問題,請考慮將其重寫為獨立函數,而不是原型函數。

暫無
暫無

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

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