Javascript:我如何在不同的类之间进行通信?

Mar*_*zzo 0 javascript oop inheritance class

我正在尝试使用Javascript中的类(感谢本指南).我已经学会了如何创建类的实例,以及如何嵌套它们,但我不知道如何让子类与其父类进行通信.

这是我的基本示例:我有一个具有数组的Board类allPieces,其中包含20 Piece个子对象.

function Board(){
    this.allPieces = [];
    this.selectedPiece = null;
    for(var i = 0; i < 20; i++){
        this.allPieces.push(new Piece(i));
    }
}

Board.prototype.makeSelection = function(currentPiece){
    this.selectedPiece = currentPiece;
}

function Piece(index){
    this.type = index;
    this.jqObject = $(".piece").eq(this.type);
    this.jqObject.click(function(){
        this.pieceClicked();
    }.bind(this));
}

Piece.prototype.pieceClicked = function(){
    Board.makeSelection(this); // <------ This gives me an error!
    // How do I tell Board that a selection has been made?
}

new Board();
Run Code Online (Sandbox Code Playgroud)

我可以通过电话从董事会沟通到一this.allPieces[0].anyMethod()件事但是,我不知道如果点击它就会从Piece传递到它的父母董事会; 我收到错误"Board.makeSelection不是函数".我如何告诉董事会已选择一件作品?

我已经尝试将一个var名称分配给Board var game = new Board();然后调用,game.makeSelection(this);但问题是这只允许一次一个Board实例.我需要有多个实例.有什么建议?

rav*_*ano 6

为了实现这一点,您需要在各个部分上建立某种双向数据绑定.您可以通过执行以下操作来完成此操作.

首先,您修改了piece类,以便它知道它的父类:

function Piece(index, parent){ // notice the second argument
  this.parent = parent; // we're going to store a reference to the parent here
  this.type = index;
  this.jqObject = $(".piece").eq(this.type);
  this.jqObject.click(function(){
    this.pieceClicked();
  }.bind(this));
}

Piece.prototype.pieceClicked = function(){
  this.parent.makeSelection(this); // we'll access the makeSelection method from the parent
}
Run Code Online (Sandbox Code Playgroud)

然后,您修改了Board类,以便它将自身作为第二个参数传递给创建该块:

function Board(){
  this.allPieces = [];
  this.selectedPiece = null;
  for(var i = 0; i < 20; i++){
    this.allPieces.push(new Piece(i, this)); 
    // we'll invoke the piece with a second argument which will be the parent (the board)
  }
}
Run Code Online (Sandbox Code Playgroud)

这将允许每件作品通过访问该作品上的this.parent属性来了解其父作品.然后,您可以通过访问this.parent.makeSelection并将其作为参数传入来访问父项的make选择方法.