【问题标题】:Add a method to prototype of js object向 js 对象的原型添加方法
【发布时间】:2014-07-17 07:52:58
【问题描述】:

试图给jsDate对象添加一个方法来获取格式化日期,Date没有在任何地方声明或者用new/create()调用:

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();时抛出错误:undefined is not a function

请说明如何在其原型中使用单一对象类型的其他方法。

【问题讨论】:

  • 为我工作:new Date().format() - "2014-7-17"
  • 对不起,它也开始为我工作了。
  • 这个问题应该被关闭,因为它是由无法再重现的问题引起的。

标签: javascript methods prototype add


【解决方案1】:

如果您想在不创建新的日期实例的情况下使用它...呵呵

你可以的

 var d = new Date 

在一个函数中。并将所有 THIS 替换为 d。然后就可以了

Date.prototype.format()

但如果你仍然想要这个,那就去做吧

new Date().format()

【讨论】:

    【解决方案2】:

    您是否有可能将其称为属性而不是方法?我只是将您的代码放入 Chrome 的控制台,通过将其作为方法调用,它似乎可以正常工作。

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

    如果您仍然遇到问题,请考虑将其重写为独立函数,而不是原型函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2013-09-23
      • 2018-03-17
      • 2014-05-26
      • 2019-01-17
      • 2016-09-03
      相关资源
      最近更新 更多