2
我試圖使用繼承在JavaScriptJavascript繼承不能使用基類的方法
我這裏是C#代碼來顯示我試圖
public class animal
{
public animal() { }
public string move()
{
return "i'm moving";
}
public string bite()
{
return "just a nip!";
}
}
public class snake : animal
{
public snake() { }
public string bite()
{
return "been poisoned!";
}
}
用作什麼:
var a = new animal();
var s = new snake();
a.bite(); // just a nip
s.bite(); // been poisoned
a.move(); // i'm moving
s.move(); // i'm moving
現在JS我有:
function animal() {
};
animal.prototype.move = function() {
return "im moving";
};
animal.prototype.bite = function() {
return "just a nip";
};
snake.prototype = new animal();
snake.prototype = snake;
function snake() {
}
snake.prototype.bite = function() {
return "been poisoned";
};
var a = new animal();
var s = new snake();
alert(a.bite()); // just a nip
alert(s.bite()); // been poisoned
alert(a.move()); //i'm moving
alert(s.move()); // s.move is not a function
我是否必須在每個子類中提供方法並調用基本方法?即添加一個移動方法蛇來調用animal.move?
snake.prototype.move = function() {
return animal.prototype.move.call(this);
}
沒錯這就是它!謝謝! – mth 2011-02-24 16:21:01