2

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() {
};

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);
}

1 Answer 1

4

right now you set the prototype twice.

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

the second line should be

snake.prototype.constructor = snake;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.