问题描述
我搜索了如何继承对象,我发现您可以使用 Create()
函数,但它不起作用。
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 是一个数组,如果我做一个新鼠标,它不知道 can_move
是什么:
Uncaught TypeError: Board[2][6].animal.can_move is not a function,animal is just an
attribute of board,it contains Mouse.
编辑:谢谢,但现在它给了我:
Cannot set property 'can_move' of undefined
at new Animal.
解决方法
您需要确保在 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());
使用类更容易
class Animal {
can_move(){ return true; }
}
class Mouse extends Animal {}
const m = new Mouse();
console.log(m.can_move());