这个问题并非特定于 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
另一个伪变量应该以相同的方式处理 - 通过别名。