簡體   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