Evald
Evald

Reputation: 122

Creating multiple objects with same variables

I cannot figure out how to create several objects from the main object

Here is what i am trying to do:

var player = {
    var totalScore = 0;
    var playing = true;
    function checkScore() {
       if (totalScore >= 100) {
            playing = false;
       }
    };
};

player playerAI = new player();
player playerOne = new player();

Upvotes: 0

Views: 1278

Answers (4)

frogatto
frogatto

Reputation: 29285

// 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;
    };
};

Usage:

var player1 = new Player();
console.log(player1.isPlaying());

Note: It's better to declare your methods as properties of the Player.prototype object. (For memory saving)

Player.protoype.isPlaying = function (){
    return this.playing;
};

Upvotes: 0

Paul S.
Paul S.

Reputation: 66354

I've re-written your code as a Constructor in 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();

Some of your code patterns don't look like JavaScript though, are you sure you're not using a different language? (such as Java)

Upvotes: 2

Jiang
Jiang

Reputation: 588

I'm not sure if this is what you want:

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();

Upvotes: 0

dekajoo
dekajoo

Reputation: 2102

try this :

var player = function() {
    this.totalScore = 0;
    this.checkScore = function() {
        if (totalScore >= 100) {
        playing = false;
    }    
};
player playerAI = new player();
player playerOne = new player();

Upvotes: 0

Related Questions