2011-02-24 71 views
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); 
} 

回答

4

现在你设置了原型两次。

snake.prototype = new animal(); 
snake.prototype = snake; 

第二行应该是

snake.prototype.constructor = snake; 
+0

没错这就是它!谢谢! – mth 2011-02-24 16:21:01