JavaScript Function bind()
- Önceki Sayfa JS Fonksiyon Apply
- Sonraki Sayfa JS Kapalı
Fonksiyon Borrowing
bind() yöntemi kullanılarak, bir nesne diğer bir nesnenin bir yöntemini借用 edebilir.
Aşağıdaki örnek, 2 nesne (person ve member) oluşturur.
member nesnesi person nesnesinin fullname yöntemini kullandı:
örnek
const person = { firstName: "Bill", lastName: "Gates", fullName: function () { return this.firstName + " " + this.lastName; } } const member = { firstName: "Hege", lastName: "Nilsen", } let fullName = person.fullName.bind(member);
this'i kaybetmemek için
bind() yöntemini kullanmak zorunda kalabiliriz ki bu, this.
Bu örnekte, person nesnesi bir display yöntemine sahiptir. Display yönteminde,this person nesnesini belirtir:
örnek
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } person.display();
Fonksiyon geri çağrı olarak kullanıldığında,this kaybolacaktır.
Bu örnek 3 saniye sonra ismi göstermeyi deneyecek, ancak: undefined:
örnek
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } setTimeout(person.display, 3000);
bind() yöntemi bu sorunu çözer.
bind() yöntemi, person.display'i person'a bağlamak için kullanılır.
Bu örnek, 3 saniye sonra ismi görüntülemek için:
örnek
const person = { firstName: "Bill", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } let display = person.display.bind(person); setTimeout(display, 3000);
What is this?
JavaScript'te,this
Anahtar kelime ifade edenNesne.
İfade edenHangiNesne, çağrı (kullanma veya çağrı) şekline bağlıdır.
Kullanım şekline göre, anahtar kelime this
Farklı nesneleri ifade eden
- Nesne yöntemlerinde,
this
Bu nesneyi ifade edenNesne. - Birisini kullanarak
this
İfade edenKüresel nesne. - Fonksiyonda,
this
İfade edenKüresel nesne. - Fonksiyonda, katı modda,
this
değeriundefined
. - Olayda,
this
Olay alanını alanElement. - call()、apply() ve bind() gibi yöntemler
this
İfade edenHerhangi bir nesne.
Dikkat:this
Değişken değil. Bir anahtar kelime. Değiştiremezsiniz this
Değeri.
Ayrıca bakınız:
Eğitim:JavaScript this
- Önceki Sayfa JS Fonksiyon Apply
- Sonraki Sayfa JS Kapalı