понеделник, 18 септември 2017 г.

Explaining the Bind Method in JavaScript

Functions in JavaScript are objects. As objects, functions possess methods, including the powerful Bind method. Bind is used for setting the this value in methods, borrowing methods of other objects and for currying functions. Bind method is primarily used to call a function with the this value set explicitly. It enables us to easily set which specific object will be bound to this when a function is invoked. The need for bind occurs when this keyword in a method is not bound to the object that we expect it to be bound to - usually calling that method from a receiver object.

var person = {
    name: "Terry Smith",
    age: 43,
    print: function (event) {
        console.log(this.name + ", age: " + this.age);  ​
    }
};
 
//Invoke the person's print method on button's click event​
$("button").click (person.print.bind(person));
 

Няма коментари:

Публикуване на коментар