JavaScript Function bind()
- ਪਿਛਲਾ ਪੰਨਾ JS ਫੰਕਸ਼ਨ Apply
- ਅਗਲਾ ਪੰਨਾ JS ਬੰਦ ਸ਼ੂਟ
ਫੰਕਸ਼ਨ ਲੋਣ (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
- ਪਿਛਲਾ ਪੰਨਾ JS ਫੰਕਸ਼ਨ Apply
- ਅਗਲਾ ਪੰਨਾ JS ਬੰਦ ਸ਼ੂਟ