【问题标题】:How to extend a class inside a namespace in javascript?如何在javascript中的命名空间内扩展一个类?
【发布时间】:2017-01-25 22:13:48
【问题描述】:
var sl = sl || {}

sl.Shape = function(){
    this.x = 0;
    this.y = 0;
};
sl.Shape.prototype.move = function(x,y){
    this.x += x;
    this.y += y;
};
sl.Rectangle = function(){
    sl.Shape.call(this);
    this.z = 0;
};

下一行产生错误(对象原型未定义,必须为对象或空)。据我所知,这是因为 Shape 是“命名空间”。

sl.Rectangle.protoype = Object.create(sl.Shape.protoype);
sl.Rectangle.protoype.constructor = sl.Rectangle;

我该如何正确地做到这一点?

【问题讨论】:

    标签: javascript class namespaces prototype extend


    【解决方案1】:

    您应该使用单词原型而不是原型。

    【讨论】:

    • 谢谢,带我到凌晨 4 点才看到,即使是你写的内容!!
    【解决方案2】:

    正如 Andrii 指出的那样,你拼错了“原型”这个词,试试这个例子:

    (function() {
      var sl = sl || {};
    
      function Shape() {
        this.x = 0;
        this.y = 0;
      }
    
      Shape.prototype.move = function(x, y) {
        this.x += x;
        this.y += y;
      };
    
      function Rectangle() {
        Shape.apply(this, arguments);
        this.z = 0;
      };
    
      Rectangle.prototype = Object.create(Shape.prototype);
      Rectangle.prototype.constructor = Rectangle;
    
      sl.Shape = Shape;
      sl.Rectangle = Rectangle;
    
      // expose
      window.sl = sl;
    }());
    

    用法

    var shape = new sl.Shape();
    var rect = new sl.Rectangle();
    

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2023-03-14
      • 2012-09-02
      相关资源
      最近更新 更多