danny
danny

Reputation: 72

Javascript inheritance is not working, using the prototype method

I searched on how to inherit an Object and I found that you can use the Create() function but it doesn't work.

function Animal(strength, team, id /*url*/ ) {
  this.strength = strength;
  this.team = team;
  this.id = id;
  this.can_move = function(position, destination) {
    this.destination = Board[destination[0]][destination[1]]
    if ((position[0] == destination[0] + 1) && (position[1] == destination[1]) ||
      (position[0] == destination[0] - 1) && (position[1] == destination[1]) ||
      (position[1] == destination[1] + 1) && (position[0] == destination[0]) ||
      (position[1] == destination[1] - 1) && (position[0] == destination[0])) {} else {
      console.log('false')
      return false
    }

    if (Board[destination[0]][destination[1]].animal != null) {
      if (this.can_eat(Board[destination[0]][destination[1]].animal)) {
        /*pass*/ } else {
        console.log('false')
        return false
      }
    }
    if (!this.obstacle()) {
      return false;
    }

    console.log('true')
    return true
  }
  this.can_eat = function(animal) {
    if (animal.strength <= this.strength) {
      return true
    } else {
      return false
    }
  }
  this.obstacle = function() {
    if (Board[destination[0]][destination[1]].type == "River1" || Board[destination[0]][destination[1]].type == "River2" ||
      Board[destination[0]][destination[1]].type == team + "_goal") {
      console.log("false");
      return false;
    }
  }
  this.move = function(position, destination) {
    //pass
  }
}

function Mouse(team, id) {

}
Mouse.prototype = Object.create(Animal.prototype);

Board is an array and if I do a new Mouse it doesn't know what can_move is:

Uncaught TypeError: Board[2][6].animal.can_move is not a function, animal is just an 
attribute of board, it contains Mouse.

Edit: Thanks,but now it gives me:

Cannot set property 'can_move' of undefined
at new Animal.

Upvotes: 2

Views: 71

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You need to make sure you're declaring your functions on the prototype of Animal

function Animal(){

}
Animal.prototype.can_move = function(){ return true; }

function Mouse(){

}
Mouse.prototype = Object.create(Animal.prototype);

const m = new Mouse();
console.log(m.can_move());

This is a lot easier using classes

class Animal {
   can_move(){ return true; }
}

class Mouse extends Animal {}

const m = new Mouse();
console.log(m.can_move());

Upvotes: 1

Related Questions