Javascript继承无法使用基类方法

时间:2011-02-24 16:11:04

标签: javascript inheritance

我正在尝试在javascript中使用继承

这里是示例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);
}

1 个答案:

答案 0 :(得分:4)

现在你将原型设置了两次。

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

第二行应该是

snake.prototype.constructor = snake;