为什么在JavaScript中使用递归函数时会更改“ this”?

时间:2019-06-02 11:28:01

标签: javascript node.js recursion

我写了很多很好用的递归函数,但是我对此有疑问。我有一个包含两个矩阵的模块。因此,在递归函数内部,我通过this关键字使用这些矩阵。初次通话效果很好,但是this的内容却不同,我无法访问矩阵!

这是我的代码:

index.js:

var TileAttack = require('./lib/problem/AttackedTier/TileAttack').TileAttack;
this.board = [
    [0, 1, 0],
    [1, 0, 0],
    [0, 0, 1]
];
this.attackBoard = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
];
this.tileAttack = TileAttack;
this.tileAttack.init(this.board);
this.tileAttack.checkDown(0, 0, this.tileAttack.isQueenIn(0, 0));

TileAttack.js:

let board;
let attackBoard;
let boardSize;

function init(board) {    
    this.board = board;
    this.attackBoard = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ];
    this.boardSize = this.board.length;
}

function checkRight(i, j, wasQueenInPath) {             
    checkAttack(i, j, wasQueenInPath, i, j + 1, checkRight);
}

function checkDown(i, j, wasQueenInPath) {
    checkAttack(i, j, wasQueenInPath, i + 1, j, checkDown);
}

function checkAttack(currentI, currentJ, wasQueenInPath, nextI, nextJ, 
                  currentMove) {
    let queenSeen = false;
    if (currentI >= this.boardSize) return queenSeen;

    if (isQueenIn(currentI, currentJ)) {
        queenSeen = true;
        currentMove(nextI, nextJ, queenSeen);
        return queenSeen;
    }

    if (wasQueenInPath) this.attackBoard[currentI][currentJ]++;

    queenSeen = currentMove(nextI, nextJ, wasQueenInPath);
    if (queenSeen) {
        this.attackBoard[currentI][currentJ]++;
        return queenSeen;
    }
}

function isQueenIn(i, j) {
    return this.board[i][j] == 1;
}

exports.TileAttack = {init, checkDown, checkRight, isQueenIn}

与以前的尝试不同的是,我在这里导出了一个函数对象。在以前的示例中,我只是导出一个函数。

编辑

这些代码效果很好:

function sort(low, high) {
    if (high <= low) return;

    let pivotIndex = partition(low, high);
    sort(low, pivotIndex - 1);
    sort(pivotIndex + 1, high);
}

function partition(low, high) {
    let pivot = this.arr[low];    
    let pivotIndex = low;
    for (i = low + 1; i <= high; i++){
        if (pivot > this.arr[i]) {
            pivotIndex++;
            exchange(i, pivotIndex);            
        }            
    }
    exchange(low, pivotIndex);    
    return pivotIndex;
}

我的第二个密码和第一个密码有什么区别?谁能解决这个问题?

0 个答案:

没有答案