[英]Variable Scope - jQuery/JavaScript
I'm having a bit of trouble with variable scope within jQuery/JavaScript. 我在jQuery / JavaScript中使用变量范围有点麻烦。 I'll just give a code example demonstrating my issue as it's probably easier to understand than trying to explain with words. 我只给出一个代码示例来演示我的问题,因为它可能比尝试用单词解释更容易理解。
var example_1 = function() {
row = 10;
}
var example_2 = function() {
something.click(function(){
var something_3 = function() {
alert(row);
}
something_3();
}
}
The problem is, the row variable cannot be accessed within the something_3 function. 问题是,无法在something_3函数中访问行变量。 I have other variables from the example_1 function being accessed in the example_2 function, but when put in the something_3 function it no longer works. 我在example_2函数中访问了来自example_1函数的其他变量,但是当将它们放入something_3函数时,它将不再起作用。 Thanks for any help! 谢谢你的帮助!
Edit: Added extra code to show what works and what isn't. 编辑:添加了额外的代码以显示什么有效,什么无效。 Row is defined within the Build function as are board and mines. 行在Build函数中定义,木板和地雷也是如此。 Board and mines can be accessed but row cannot. 可以访问董事会和地雷,但不能访问行。
var build = function(row) {
row = typeof row !== 'undefined' ? row : 5;
board = $('.container');
mines = [1,2,3,4];
}
build();
var start = function() {
var tile = $('.container div');
tile.click(function() {
var this_index = $(this).index();
var has_mine = $.inArray(this_index, mines);
var scan = function() {
alert(row);
}
if (has_mine > -1) {
add_alert("Has mine, you're dead!");
} else {
scan();
$(this).html('Clear!');
}
});
var add_alert = function(msg) {
board.append("<span class='alert'>" + msg + "</span>")
$('body').append("<div class='blackout'></div>");
}
}
start();
Multiple issues: 多个问题:
EDIT 2: 编辑2:
var build = function(row) {};
ok so your issue is the row variable is a parameter so isn't a global variable anymore. 好的,所以您的问题是行变量是一个参数,因此不再是全局变量 。 If you remove your row parameter / update variable name passed to build method, it will work. 如果删除传递给build方法的行参数/更新变量名,它将起作用。
var build = function(row) {
row = typeof row !== 'undefined' ? row : 5;
//[...]
}
row
is not being defined as a variable, but instead is a parameter. row
未定义为变量,而是参数。 This way, it doesn't leak as a global variable. 这样,它就不会作为全局变量泄漏。
Simply changing the name of parameter should work: 只需更改参数名称即可:
var build = function(rowValue) {
row = typeof rowValue !== 'undefined' ? rowValue: 5;
//[...]
}
However, you shouldn't be using implicitly global variable. 但是,您不应该使用隐式全局变量。 Global variables are already bad enough. 全局变量已经足够糟糕了。
Option one, declaring variables: 选项一,声明变量:
var row, board, mines;
var build = function(rowValue) {
row = typeof rowValue !== 'undefined' ? rowValue : 5;
board = $('.container');
mines = [1,2,3,4];
}
Option two, using the global identifier: 方法二,使用全局标识符:
var build = function(row) {
window.row = typeof row !== 'undefined' ? row : 5;
window.board = $('.container');
window.mines = [1,2,3,4];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.