Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Function Bind

JS Function Bind

With the bind() method, an object can borrow a method from another object.

					 
        
          const person = {
            firstName:"John",
            lastName: "Doe",
            fullName: function () {
              return this.firstName + " " + this.lastName;
            }
          }

          const member = {
            firstName:"Hege",
            lastName: "Nilsen",
          }

          let fullName = person.fullName.bind(member);
        
      
Preserving this

Sometimes the bind() method has to be used to prevent losing this.

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

          person.display();
        
      

When a function is used as a callback, this is lost.

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

          setTimeout(person.display, 3000);
        
      

The bind() method solves this problem.

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

          let display = person.display.bind(person);
          setTimeout(display, 3000);
        
      

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved