如何在javascript中扩展名称空间中的类?

时间:2016-09-17 23:05:02

标签: javascript class namespaces prototype extend

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

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

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

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

2 个答案:

答案 0 :(得分:1)

你应该使用word prototype而不是protoype。

答案 1 :(得分:0)

你拼错了单词" prototype"正如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();