如何解决Javascript 继承不起作用,使用原型方法
我搜索了如何继承对象,我发现您可以使用 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());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。