Binding in Javascript example!

Javascript Binding in English simplified!


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

// 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.