Как расширить класс внутри пространства имен в 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;
};
Следующая строка выдает ошибку (прототип объекта не определен, должен быть объект или ноль). Насколько я понимаю, это потому, что Shape "namespaced".
sl.Rectangle.protoype = Object.create(sl.Shape.protoype);
sl.Rectangle.protoype.constructor = sl.Rectangle;
Как мне сделать это правильно?
2 ответа
Решение
Вы неправильно написали слово "прототип", как указал Андрей, попробуйте этот пример:
(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();