この質問は 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
同じように扱われるべき他の疑似変数です — エイリアシングによる.