[英]why is my javascript object method returning undefined?
我也是javascript oop和游戏编程的初学者(!)。 在这里,我用一种方法创建了一个玩家。 但该方法返回未定义。 这是为什么?,
bobsGame = {};
bobsGame.player = function(which){
this.which = which;
this.rollDice = function () {
diceVal = Math.floor(Math.random() * 6 + 1);
console.log(diceVal);
return diceVal;
}
}
var player1 = new bobsGame.player('player1');
然后在标记中…
$('#roll-dice-btn-1').click(function(){
bobsGame.player1.rollDice();
});
您的课程中没有bobsGame.player1
,您只是实例化了一个变量player1
的新实例?
var player1 = new bobsGame.player('player1');
$('#roll-dice-btn-1').click(function(){
player1.rollDice();
});
您的电话应该是player1.rollDice()
类的
$('#roll-dice-btn-1').click(function(){
player1.rollDice();
});
您在bobsGame对象的player
属性和实际创建的player1
对象之间感到困惑。
这可能会更好
bobsGame.player1 = new bobsGame.player('player1');
您可以使用以下结构:
bobsGame = function(opts) {
this.player = opts.player;
this.diceVal = 0;
}
bobsGame.prototype.rollDice = function(){
this.diceVal = Math.floor(Math.random() * 6 + 1);
}
并在您的主文件中:
var player1 = new bobsGame({player: 'player1'});
$('#roll-dice-btn-1').click(function(){
player1.rollDice();
console.log(player1.diceVal);
});
您的小问题。 它无法在您的课程中找到bobsGame.player1
。 因此,像这样进行更改,它将可以正常工作。
bobsGame.player = function(which){
this.which = which;
this.rollDice = function(){
diceVal = Math.floor(Math.random() * 6 + 1);
console.log(diceVal);
return diceVal;
}
}
var player1 = new bobsGame.player('player1');
player1.rollDice();
bobsGame.player1
是不确定的,因为player1
没有对象中声明bobsGame
。
如果要创建player1
作为bobsGame
对象中的键,则必须使用bobsGame.player1 = new bobsGame.player('player1');
代替。 因此您的代码如下所示:bobsGame = {};
bobsGame.player = function(which){
this.which = which;
this.rollDice = function () {
diceVal = Math.floor(Math.random() * 6 + 1);
console.log(diceVal);
return diceVal;
}
}
var player1 = new bobsGame.player('player1');
否则,您可以使用:
$('#roll-dice-btn-1').click(function(){
player1.rollDice();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.