3 Aralık 2008, ÇARŞAMBA
öz = bu var?
Olay işleyicileri için geri çağrıları örnek yöntemleri kullanarak this
kapsamını değiştirir"Benim örnek"içinSadece geri çağırdı "ne". Benim kod bu gibi görünüyor
function MyObject() {
this.doSomething = function() {
...
}
var self = this
$('#foobar').bind('click', function(){
self.doSomethng()
// this.doSomething() would not work here
})
}
Çalışır, ama bunu yapmanın en iyi yolu nedir? Bana garip görünüyor.
CEVAP
3 Aralık 2008, ÇARŞAMBA
Bu soruya belirli bir DV ancak belirli genel olarak JavaScript değil. Temel sorun, "gömülü fonksiyonlar." değişken bir kanal nasıl olur Bu bir örnektir:
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!
}
...
};
Bu teknik bir kapatma kullanarak dayanır. Ama this
kapsam dinamik kapsam değişebilir sahte bir değişken olduğundan this
ile çalışmıyor:
// 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!
}
...
};
Ne yapabiliriz? Bazı değişken atamak ve diğer adı ile kullanın:
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
bu konuda benzersiz değildir: arguments
aynı şekilde & - aliasing tarafından ele alınması gerektiğini diğer sahte değişkendir.
Bunu Paylaş: