2016-09-17 115 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或null)。據我所見,這是因爲Shape是「命名空間」。如何在JavaScript中的命名空間內擴展一個類?

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

如何正確地做到這一點?

回答

1

您應該使用word原型而不是原型。

+0

感謝,帶我到凌晨4點,看看它,甚至在你寫了! – Daniela

0

您有拼寫錯誤的單詞「原型」爲安德里指出,嘗試這個例子:

(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