JavaScript Function bind()

ਫੰਕਸ਼ਨ ਲੋਣ (Function Borrowing)

bind() ਮੈਥਡ ਦੀ ਵਰਤੋਂ ਨਾਲ ਇੱਕ ਆਬਜੈਕਟ ਦੂਜੇ ਆਬਜੈਕਟ ਦੀ ਮੈਥਡ ਲੋਣ ਸਕਦਾ ਹੈ。

ਨਿਚੇ ਦੇ ਉਦਾਹਰਣ ਵਿੱਚ 2 ਆਬਜੈਕਟ (person ਅਤੇ member) ਬਣਾਏ ਗਏ ਹਨ。

member ਆਬਜੈਕਟ ਨੇ person ਆਬਜੈਕਟ ਦੀ fullname ਮੈਥਡ ਲੋਣੀ ਹੈ:

ਉਦਾਹਰਣ

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 ਬਣਾਏ ਰਹੇ

bind() ਮੈਥਡ ਵਰਤਣਾ ਹੋਵੇਗਾ ਤਾਂ ਹੀ ਇਹ ਹਾਨੀ ਰੋਕੀ ਜਾ ਸਕੇਗੀ this

ਨਿਚੇ ਦੇ ਉਦਾਹਰਣ ਵਿੱਚ person ਆਬਜੈਕਟ ਨੂੰ ਇੱਕ display ਮੈਥਡ ਹੈ। ਵਿਕਲਪ display ਮੈਥਡ ਵਿੱਚthis ਇਹ person ਆਬਜੈਕਟ ਹੈ:

ਉਦਾਹਰਣ

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 ਹੈ?

ਜਿਸ ਵਿੱਚthis ਕੀਵਾਰਡ ਸਬੰਧਤ ਕਰਦਾ ਹੈਆਬਜੈਕਟ

ਸਬੰਧਤ ਕਰਦਾ ਹੈਜਿਸਆਬਜੈਕਟ ਦੇ ਵਰਤੋਂ ਤੋਂ ਨਿਰਭਰ ਕਰਦਾ ਹੈ

ਕੀਵਾਰਡ this ਵੱਖ-ਵੱਖ ਆਬਜੈਕਟਾਂ ਨੂੰ ਸਬੰਧਤ ਕਰਦਾ ਹੈ

  • ਆਬਜੈਕਟ ਮੰਥਨ ਵਿੱਚthis ਇਸ ਨੂੰ ਸਬੰਧਤ ਕਰਦਾ ਹੈਆਬਜੈਕਟ
  • ਅਲੱਗ-ਅਲੱਗ ਵਰਤੋਂ ਵਿੱਚthis ਸਬੰਧਤ ਕਰਦਾ ਹੈਗਲੋਬਲ ਆਬਜੈਕਟ
  • ਫੰਕਸ਼ਨ ਵਿੱਚthis ਸਬੰਧਤ ਕਰਦਾ ਹੈਗਲੋਬਲ ਆਬਜੈਕਟ
  • ਫੰਕਸ਼ਨ ਵਿੱਚ, ਸਖਤ ਮੋਡ ਵਿੱਚthis ਹੈ undefined
  • ਈਵੈਂਟ ਵਿੱਚthis ਈਵੈਂਟ ਨੂੰ ਪ੍ਰਾਪਤ ਕਰਨ ਵਾਲੇਐਲੀਮੈਂਟ
  • call()、apply() ਅਤੇ bind() ਮੰਥਨ ਸਮੇਤ this ਸਬੰਧਤ ਕਰਦਾ ਹੈਕੋਈ ਵੀ ਆਬਜੈਕਟ

ਧਿਆਨ:this ਨਹੀਂ ਹੈ ਵਾਰੀਆਂ।ਇਹ ਇੱਕ ਕੀਵਾਰਡ ਹੈ।ਤੁਸੀਂ ਇਸ ਨੂੰ ਸੋਧ ਨਹੀਂ ਸਕਦੇ this ਦੀ ਕੀਮਤ

ਹੋਰ ਦੇਖੋ:

ਅਧਿਆਪਨ:JavaScript this