【问题标题】:Extend javascript classes and wrap them in a container object扩展 javascript 类并将它们包装在容器对象中
【发布时间】:2016-05-31 08:11:05
【问题描述】:

ES6 中,您可以让您的自定义类扩展 javascript 内置对象。像这样,您可以使用自定义方法制作ArrayNumberStringDate 对象。

我正在对此进行试验,并尝试将我的对象包装在一个名为My 的容器对象中,只需遵循示例here from MDN (Mozilla Developer Network)。但是当我像这样在对象中定义我的自定义 Date 类时:

var My = {};

class My.Date extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

我收到以下 SyntaxError

Uncaught SyntaxError: Unexpected token .

Here is a fiddle 证明了这一点。

我敢打赌有一些方法可以解决这个问题,但我不知道该怎么做......

【问题讨论】:

  • 你不能在你的类名中使用.
  • 查看link 了解有关标识符名称的官方信息

标签: javascript ecmascript-6 containers extends


【解决方案1】:

不允许在你的类名中使用.。但是可以将类实例添加到您的命名空间。

var My = {};

class MyDate extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

My.Date = MyDate;

或者直接

var My = {};

My.Date = class MyDate extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

【讨论】:

    【解决方案2】:

    解决方法是将逻辑包装在函数中,以便在函数本地范围内声明新类,然后将其添加到函数内的全局 My 容器中。
    像这样,您可以使用自定义对象(扩展原语)而不会弄乱全局对象,它们看起来仍然相似(例如,在控制台中打印时类名是 Date)。

    var My = {};
    
    function init(){
    
        class Date extends window.Date {
            constructor() {
                super();
            }
    
            getFormattedDate() {
                var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
            }
        }
    
        My.Date = Date;
    
    }
    
    init();
    
    Date === window.Date; // true
    My.Date === window.Date; // false
    My.Date.name // Date -> class name
    new My.Date().getFormattedDate(); // 2-Jun-2016
    

    this answer here的另一个解决方案:

    var My = {};
    
    My.Date = class extends Date {
        constructor() {
            super();
        }
    
        getFormattedDate() {
            var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      相关资源
      最近更新 更多