我无法弄清楚如何从主对象
创建多个对象以下是我要做的事情:
var player = {
var totalScore = 0;
var playing = true;
function checkScore() {
if (totalScore >= 100) {
playing = false;
}
};
};
player playerAI = new player();
player playerOne = new player();
答案 0 :(得分:2)
我已在 JavaScript
中将您的代码重写为构造函数function Player() {
this.totalScore = 0; // `this` will refer to the instance
this.playing = true;
}
Player.prototype.checkScore = function () { // the prototype is for shared methods
if (this.totalScore >= 100) { // that every instance will inherit
this.playing = false;
}
};
var playerAI = new Player(),
playerOne = new Player();
但是,您的某些代码模式看起来并不像 JavaScript ,您确定自己并未使用其他语言吗? (比如Java)
答案 1 :(得分:0)
试试这个:
var player = function() {
this.totalScore = 0;
this.checkScore = function() {
if (totalScore >= 100) {
playing = false;
}
};
player playerAI = new player();
player playerOne = new player();
答案 2 :(得分:0)
// Define a constructor function
var Player = function () {
// This acts as public property
this.playing = true;
// This acts as public method
this.isPlaying = function (){
return this.playing;
};
};
用法:
var player1 = new Player();
console.log(player1.isPlaying());
注意:最好将方法声明为Player.prototype
对象的属性。 (节省内存)
Player.protoype.isPlaying = function (){
return this.playing;
};
答案 3 :(得分:0)
我不确定这是不是你想要的:
function player() {
var totalScore = 0;
var playing = true;
return {
checkScore: function checkScore() {
if (totalScore >= 100) {
playing = false;
}
}
}
};
var playerAI = new player();
var playerOne = new player();