2015-02-06 128 views
0

如何擴展原型並向其添加新的方法?例如,我想將形狀(超類)擴展爲子類 - 矩形。我延長它,因爲我想使用的方法形狀,但添加更多方法(和覆蓋一些形狀的方法也一樣)在矩形JavaScript本地原型:擴展,添加和覆蓋方法?

但我不能利用/ 添加方法矩形後訪問方法形狀了,

// Shape - superclass 
function Shape() { 
    this.x = 0; 
    this.y = 0; 
} 

// superclass method 
Shape.prototype.move = function(x, y) { 
    this.x += x; 
    this.y += y; 
    console.info('Shape moved.'); 
}; 

// Rectangle - subclass 
function Rectangle() { 
    Shape.call(this); // call super constructor. 
} 

// subclass extends superclass 
Rectangle.prototype = Object.create(Shape.prototype); 
Rectangle.prototype.constructor = Rectangle; 

Rectangle.prototype = { 
    jump : function(){ 
     return 'Shape jumped'; 
    } 
}; 

var rect = new Rectangle(); 

console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true 
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true 
rect.move(1, 1); // TypeError: rect.move is not a function 

我之後的結果,

// Outputs, 'Shape moved.' 

任何想法我錯過了什麼?

+2

您沒有運行你發佈的代碼。 'rect instanceof Shape'返回false(因爲* Rectangle.prototype *不再繼承* Shape.prototype *)。 – RobG 2015-02-06 10:40:36

+0

你是對的。我的錯誤... – laukok 2015-02-06 12:21:24

回答

3

您在這裏覆蓋Rectangle.prototype

Rectangle.prototype = { 
    jump : function(){ 
     return 'Shape jumped'; 
    } 
}; 

您應該添加到它,而不是:

Rectangle.prototype.jump = function(){ 
    return 'Shape jumped'; 
} 
+0

Awww ...明白了!謝謝。 – laukok 2015-02-06 10:39:24