Binding in Javascript example!

Javascript Binding in English simplified!

credit

To attach an object to the scope & context of a function the function bind is used. The attachment of the scope & context is called as binding.

Here is an example:


let object1 = {x:1, y:2};
let object2 = {x:10, y:20};

function printThis(){
    // the bound object is referenced using the this keyword
    console.log(this);
}

// bind an object to a function
let bindprintThis_To_object1 = printThis.bind(object1);

let bindprintThis_To_object2 = printThis.bind(object2);

bindprintThis_To_object1() // {x:1, y:2}
bindprintThis_To_object2() // {x:10, y:20}

The context this will change depending on what is bind to printThis.



Nordible is a digital solutions provider helping organizations achieve their digital goals.

We develop and measure digital solutions, implement impactful brand promotion and SEO strategies and develop software driven by rigorous testing that help your business succeed online and beyond.

You can contact us at info@nordible.com for business inquiries.

Follow us: