如何在 javascript 的命名空间内扩展 class?

How to extend a class inside a namespace in javascript?

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;
};

下一行产生错误(对象原型未定义,必须是对象或 null)。据我所知,这是因为 Shape 是 "namespaced".

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

如何正确执行此操作?

你应该使用 prototype 这个词而不是 protoype。

正如 Andrii 指出的那样,您拼错了单词 "prototype",试试这个例子:

(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();