JavaScript Function bind()

အခွင့်အရေး အပြုအမူ

bind() စက္ကန့် အသုံးပြုလိုက်ရာ

အောက်ရှိ အမျိုးသားအမည် 2 အရပ် (person နှင့် member) ကို ဖန်တီးလိုက်သည်

member အရပ် အတွက် person အရပ် အား ဘယ်အပ်လိုက်သည်

အကြောင်း

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

အချိန်ကို ပြုလုပ်လိုက်ရာ this

အောက်ရှိ အမျိုးသားအမည် အပြုအမူ အတွက် person အရပ်ကို ပြုလုပ်သည်this ဆိုလိုသည် ဖြစ်သည်

အကြောင်း

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
person.display();

亲自试一试

အခွင့်အရေး အပြုအမူ အား အသုံးပြုလိုက်ရာthis ပျောက်သွားလိမ့်မည်

အမျိုးသားအမည် 3 စက္ကန့် ပြုလုပ်လိမ့်မည် သော်လည်း ပြုလုပ်လိမ့်မည် undefined:

အကြောင်း

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
setTimeout(person.display, 3000);

亲自试一试

bind() စက္ကန့် အခင်းအမျိုးအခြားကို ပြုလုပ်သည်

အောက်ရှိ အမျိုးသားအမည် အပြုအမူ bind() စက္ကန့် person.display ကို person သို့ ဘယ်အပ်လိုက်သည်

အမျိုးသားအမည် 3 စက္ကန့် အကြာ ပြုလုပ်လိမ့်မည်

အကြောင်း

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

亲自试一试

什么是 this?

在 JavaScript 中,this 关键字引用对象

引用哪个对象取决于调用(使用或调用)的方式。

根据其使用方式,关键字 this 引用不同的对象:

  • 在对象方法中,this 引用该对象
  • 单独使用时,this 引用全局对象
  • 在函数中,this 引用全局对象
  • 在函数中,在严格模式下,thisundefined
  • 在事件中,this 引用接收事件的元素
  • call()、apply() 和 bind() 等方法可以将 this 引用到任何对象

注意:this 不是变量。它是一个关键字。您无法修改 this 的值。

另请参阅:

教程:JavaScript this