Javascript Bind Method
Bind Method के जरिए एक common function को किसी object से bind किया जा सकता है जिसके जरिए उस function से जरुरत के हिसाब से अलग अलग results दी जा सकती है |
bind method एक object के साथ function को bind करता तो है पर जब उस function को call किया जाता है तब bind method एक function का copy return करता है |
उदाहरण:
<script> let object1 = { name: "maya", city: "delhi", getdetails : function(){ console.log(`My name is '${this.name}' and I am staying at '${this.city}'.`) } } let object2 = { name: "Dhanu", city: "Mumbai", } let show = object1.getdetails.bind(object2); show(); </script>
उदाहरण में देखिए object2 में getdetails() function नहीं है, इसीलिए ये object1 से borrow किया और bind method के जरिए एक copy create किया और उस copy को show() के जरिए display किया है |
bind method से एक object से दुसरे object में function borrow कर सकतें हैं और उसका copy बनाकर result display कर सकतें हैं |
output:
bind method with arguments
bind method में पहला argument उस object को refer करता है जिससे इसे bind करना होता है | और अगर normal arguments देना है तब 2nd arguments से सुरु करना होता है |
चलिए ऊपर के उदाहरण में देखते हैं जहाँ function में extra argument भेजेंगे |
उदाहरण
<script> let object1 = { name: "maya", city: "delhi", getdetails : function(food){ console.log(`My name is '${this.name}' and I am staying at '${this.city}' and i love '${food}'.`) } } let object2 = { name: "Dhanu", city: "Mumbai", } let show = object1.getdetails.bind(object2,'chocklate'); show(); </script>
उदाहरण में देखिए food argument को getdetails() function में assign किया है और जब bind method के जरिए call किया गया तो argument को 2nd parameter में भेजा गया है |
output