这个问题不是特定于jQuery的,而是特定于JavaScript的。核心问题是如何在嵌入式函数中“引导”变量。下面是一个示例:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
此技术依赖于使用闭包。但它不起作用,因为它是一个伪变量,可能会从一个范围动态地变化到另一个范围:this
this
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
我们能做些什么?将其分配给某个变量,并通过别名使用它:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
在这方面不是唯一的:另一个伪变量应该以同样的方式处理 - 通过别名。arguments