title: A class within a class?
body: <p>Ideally I would like to do something like the following:</p>
  
  <pre><code>class Chess = {
    constructor() {
      this.board = ...;
      ...
    };
  
    class Square = {
      constructor(row, col) {
        this.row = row;
        this.col = col;
    };
  };
  </code></pre>
  
  <p>My main motivation is that with the Chess and Square classes defined separately something like: (this referring to the Chess class)</p>
  
  <pre><code>this.empty(square)
  </code></pre>
  
  <p>could be shortened to</p>
  
  <pre><code>square.empty()
  </code></pre>
  
  <p>which is more readable and more concise.</p>
  
  <p>Unfortunately I can't just make a</p>
  
  <pre><code>Square.empty()
  </code></pre>
  
  <p>method since the results depends on the information in the Chess class and</p>
  
  <pre><code>square.empty(chess)
  </code></pre>
  
  <p>is no real improvement.</p>
  
  <p>The reason I have a Square class is that something like</p>
  
  <pre><code>square.up()
  </code></pre>
  
  <p>seems much nicer than something like</p>
  
  <pre><code>[row, col + 1]
  </code></pre>
  
  <p>Do you have a suggestion on how I would accomplish the above? Some way to write a class within a class or something else entirely?</p>
  
  <p>EDIT:</p>
  
  <p>Following the advice from likle and alex I did the following:</p>
  
  <p>I added a context property to the Class Square</p>
  
  <pre><code>class Square = {
    constructor(context, row, col) {
      this.context = context;
      this.row = row;
      this.col = col;
    };
  };
  </code></pre>
  
  <p>Then redefined some methods from the Chess.prototype to the Square.protoype. For example:</p>
  
  <pre><code>// before
  Chess.prototype.empty = function (square) {
    return this.piece(square) === 0;
  };
  
  // after
  Square.prototype.empty = function () {
    return this.piece() === 0;
  };
  </code></pre>
  
  <p>Which meant that every time I created a Square object I need to add context. For example:</p>
  
  <pre><code>new Square(3, 4); // before
  new Square(this, 3, 4); // after
  new Square(this.context, 3, 4); // sometimes like this
  </code></pre>
  
  <p>To make the code more readable I created the following method:</p>
  
  <pre><code>Chess.prototype.createSquare = function (row, col) {
    return new Square(this, row, col);
  };
  </code></pre>
  
  <p>So a Square object can sometimes be created with</p>
  
  <pre><code>this.createSquare(3, 4);
  </code></pre>