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

时间:2014-12-17 21:53:36

标签: javascript class oop inheritance

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

这是我的基本示例:我有一个具有数组allPieces的Board类,其中包含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();

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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
}

然后,您修改了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)
  }
}

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

答案 1 :(得分:2)

构建子(Piece)时,将当前的Board(this)传递给它,以便它引用它所属的板。

function Board(){
   ...
     this.allPieces.push(new Piece(this, i));
   ...
}
// You will also need to store this reference

function Piece(parentBoard, index) {
   ...
   this.board = parentBoard;
   ...
}

// Now you can use the reference to your parent to make calls

Piece.prototype.pieceClicked = function(){
  this.board.makeSelection(this); 
}
相关问题