Método de vinculación: con este método, podemos vincular un objeto a una función común, de modo que dé un resultado diferente cuando sea necesario. El método bind() toma un objeto como argumento y crea una nueva función. Básicamente, vincular la función de retorno de la función.
Entendamos cuándo se usa el método bind.
bind the object with common function
Ejemplo 1:
Javascript
<script> const gfg = { name: "javascript", content: "prototype", feature: function () { console.log( `Help in learning ${this.name}. The topic is ${this.content}` ); } } // Simple method to feature of gfg object gfg.feature(); console.log() // Try to bind gfg object property feature // to other common function so that it // used for later use but it does not // happen here let b = gfg.feature; b(); console.log() // Now try to bind object using bind // method // bind method first argument refer // object that's why parameter gfg object let c = gfg.feature.bind(gfg); c(); </script>
Note: Bind different objects to a common function so that each object can access that function and extra functionality to objects so bind function takes any number of arguments. Example 2:
Javascript
<script> const gfg = { name: "javascript", content: "prototype", } const gfg1 = { name: "c++", content: "inheritance", } const gfg2 = { name: "java", content: "applet", } // Function which is binding with different object function features(param) { console.log(`Help in learning ${this.name}. The topic is ${this.content} and these are help in ${param}`) } // Binding obj1 abd extra functionality let bindfunc = features.bind(gfg); bindfunc("placement"); // Binding obj2 let bindfunc1 = features.bind(gfg2); bindfunc1("placement"); </script>
Publicación traducida automáticamente
Artículo escrito por surbhikumaridav y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA