繁体   English   中英

Javascript:如何在不同的班级之间交流?

[英]Javascript: How can I communicate between different classes?

我正在尝试开始使用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();

我可以通过调用this.allPieces[0].anyMethod()从Board到Piece进行通信。但是,一旦单击,我不知道如何从Piece与其父级Board进行通信。 我收到错误“ Board.makeSelection不是函数”。 我如何告诉董事会已经选择了一块?

我试过为Board指定一个var名称var game = new Board(); 然后调用game.makeSelection(this); 但是问题在于,一次只允许一个董事会成员。 我需要有多个实例。 有什么建议么?

为了做到这一点,您将需要在块上建立某种双向数据绑定。 您可以通过执行以下操作来完成此操作。

首先,您修改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
}

然后,修改电路板类,以便将其作为第二个参数传递给作品的创建:

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选择方法。

构造子代(Piece)时,将其传递给当前的董事会(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); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM