开发者

Javascript inheritance unable to use base class method

I'm trying to use inheritance in javascript

here is example C# code to show what I'm attempting

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!";
    }
}

used as:

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

now in JS I Have:

function animal() {
开发者_Go百科};

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

Do I have to provide a method in each of the subclasses and call the base method? ie add a move method to snake to call animal.move?

snake.prototype.move = function () {
    return animal.prototype.move.call(this);
}


right now you set the prototype twice.

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

the second line should be

snake.prototype.constructor = snake;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜