我正在尝试像在OOP javascript中编写一个蛙式游戏。我有几个精灵供玩家选择。我想要实现的是当用户选择特定的精灵时,它会在实例化玩家对象时更新正确的精灵。 当我尝试重新定义属性时出错。我尝试了几种解决方案但没有成功。 我做错了什么?请帮忙!
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>First Attempt: Frogger</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/dd.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-4 offset-sm-2 characters" style="border:1px solid black">
<img src="images/char-boy.png" alt="char-boy"><input type="radio" name="sprite" value="images/char-boy.png" checked="checked">
<img src="images/char-cat-girl.png" alt="char-boy"><input type="radio" name="sprite" value="images/char-cat-girl.png">
<img src="images/char-horn-girl.png" alt="char-boy"><input type="radio" name="sprite" value="images/char-horn-girl.png">
<img src="images/char-pink-girl.png" alt="char-boy"><input type="radio" name="sprite" value="images/char-pink-girl.png">
<img src="images/char-princess-girl.png" alt="char-boy"><input type="radio" name="sprite" value="images/char-princess-girl.png">
</div>
<div class="col-sm-6" id="game"></div>
</div>
</div>
<script src="js/resources.js"></script>
<script src="js/app.js"></script>
<script src="js/engine.js"></script>
</body>
</html>
JavaScript的:
var Player = function(){
//What sprite to use
this.sprite = $("input[name='sprite']:checked").val();
//initial x location
this.x = 200;
//initial y location
this.y = 400;
};
$(document).on("click", 'input:radio[name="sprite"]',
function(){
var result = $("input[name='sprite']:checked").val();
console.log(result);
Object.defineProperty(Player.prototype, 'sprite', {
get: function(){
return this.sprite;
},
set: function(result){
this.sprite = result;
}
});
}
);
答案 0 :(得分:0)
您收到错误,因为默认情况下您无法在JavaScript中重新定义属性。 See this answer for more information.如果要在对象上定义属性,它应该是播放器构造函数中的属性。
答案 1 :(得分:0)
你可以将?- name(abc,A).
A = [0w0061,0w0062,0w0063]
构造函数包装在一个闭包中,以便在实例化之前传入sprite:
Player
&#13;
答案 2 :(得分:0)
这是一个让你入门的Player类:
class Player
{
constructor(x,y)
{
var player = this;
this.x = x;
this.y = y;
this.sprite = null;
$('input:radio[name="sprite"]').click(function(){
player.sprite = $("input[name='sprite']:checked").val();
});
}
}
$(function(){
new Player(200,400);
});