我的问题是:如何从函数init外部调用函数mova?
init.mova(" A2-A3&#34);没有工作
完整的代码在这里。
这是一个棋盘系统。 我现在不知道如何从外部init调用函数mova。 init.mova不起作用。
代码:
var init = function() {
//--- start example JS ---
var board,
game = new Chess(),
statusEl = $('#status'),
fenEl = $('#fen'),
pgnEl = $('#pgn');
// do not pick up pieces if the game is over
// only pick up pieces for the side to move
var onDragStart = function(source, piece, position, orientation) {
if (game.game_over() === true ||
(game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false;
}
};
var onDrop = function(source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
if (move !== null) {
console.log(move.to);
}
// illegal move
if (move === null) return 'snapback';
updateStatus();
};
// update the board position after the piece snap
// for castling, en passant, pawn promotion
var onSnapEnd = function() {
board.position(game.fen());
};
var updateStatus = function() {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black';
}
// checkmate?
if (game.in_checkmate() === true) {
status = 'Game over, ' + moveColor + ' is in checkmate.';
}
// draw?
else if (game.in_draw() === true) {
status = 'Game over, drawn position';
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check() === true) {
status += ', ' + moveColor + ' is in check';
}
}
statusEl.html(status);
fenEl.html(game.fen());
pgnEl.html(game.pgn());
};
var cfg = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = new ChessBoard('board', cfg);
updateStatus();
//--- end example JS ---
var mova = function(positie) {
board.move(positie);
}
}; // end init()
$(document).ready(init);
init.mova(" A2-A3&#34);
答案 0 :(得分:0)
函数中定义的变量为scoped to that function。它们不能从函数外部调用。
如果您想要快速而肮脏的修复,可以在mova
函数之外定义变量init()
,然后在其中指定其值。
var mova;
var init = function() {
// etc. etc.
mova = function(positie) {
board.move(positie);
}
}
然后,mova
函数在init函数运行之后就可用了。
您可以确保在使用init初始化时调用的函数定义函数之前不要尝试使用该函数:
var mova;
var init = function() {
// etc. etc.
mova = function(positie) {
board.move(positie);
}
onInitComplete();
}
function onInitComplete() {
// function using mova function
}
考虑到程序的结构,您可能希望对除mova
以外的许多变量使用相同的技术。您可能不希望init()
函数中包含所有游戏逻辑。您可以为游戏状态在 init函数中定义一些变量,然后将它们的起始值分配给。希望有所帮助。