2016-09-17 9 views
-1
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 Prototype undefinedがObjectまたはnullでなければなりません。私が見る限り、これはShapeが "名前空間"であるためです。javascriptの名前空間の内部でクラスを拡張するには?

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

これを正しく行うにはどうすればよいですか?

答えて

1

プロトタイプの代わりに単語プロトタイプを使用する必要があります。

+0

おかげで、でも何で、それを見るために午前4時まで連れて行ってくれました書きました!! – Daniela

0

あなたが単語「プロトタイプ」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(); 
+0

ありがとうございます!よりエレガントに見えます – Daniela

関連する問題