简体   繁体   English

JavaScript继承无法使用基类方法

[英]Javascript inheritance unable to use base class method

I'm trying to use inheritance in javascript 我正在尝试在JavaScript中使用继承

here is example C# code to show what I'm attempting 这是示例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!";
    }
}

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: 现在在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

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? 即添加蛇的移动方法来调用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM