Snedden27 Snedden27 - 3 months ago 20
Javascript Question

Dealing with javascript objects

I have a function in javascript as so :

function player(){
var cards=[];
this.score=0;
var self=this;

this.addCard=addCard;
this.resetCards=resetCards;


function addCard(card){

cards.push(card);
this.score=+card.value;
}

function resetCards(){
cards=[];
score=0;
}


}


I user a constructor to call the function :

var player1=new player();


Then I call some of its enclosed functions like this

player1.addCard(someCardObject);//card someCardObject has .value say 5
player1.addCard(someCardObject);//card someCardObject has .value say 7


I expect player1.score to be 5+7=12 ,but it stays 7 .

Can anyone tell me what I am doing wrong here

Answer

You've got a simple error in addCard.

this.score=+card.value;

Should be

this.score += card.value;

In the first instance, you're setting this.score equal to card.value, while in the second one, you're adding card.value to it. Remember kids, order of operators matters!

Comments