1

I have a bit complicated JS Objects structure:

var Players = {};

Players.Player = function (color) {
  this.color = color; //the color can be either black or white
  Players[color] = this;
}
Players.Player.prototpe.Piece = function () {
  return this.parent.color //of course, this is not valid
}
new Players.Player("black");
new Players.Player("white");
new Players["black"].Piece(); //here I want to get "black"
new Players["white"].Piece(); //here I want to get "white"

I hope I described my problem well enough. I want to be able to return the color of the paret of the constructor, meaning to replace this.parent.color with a better command that will return "black" on the first piece and "white" on the second piece.

Thank you!

Reuven Karasik
  • 475
  • 5
  • 14

1 Answers1

1

Firstly there is a typo in your code

Players.Player.prototpe.Piece should be Players.Player.prototype.Piece

if you are using a browser like chrome , you can easily see and fix these errors by firing up the developer console. see How to debug in chrome

now moving on to the actual problem on returning the colors, you have to modify the code

from return this.parent.color to return this.color.this should fix the problem.

this is a keyword in javascript that can correctly identify the object instances, depending upon the context on which the function(here piece) is executing.

Players.Player.prototype.Piece = function () {
  return this.color //this is now valid
}

DEMO

Community
  • 1
  • 1
Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36