JavaScript Function bind()

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);

Try it yourself

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();

Try it yourself

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);

Try it yourself

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);

Try it yourself

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 kullanarakthis İfade edenKüresel nesne.
  • Fonksiyonda,this İfade edenKüresel nesne.
  • Fonksiyonda, katı modda,this değeri undefined.
  • 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