Skip to content

Latest commit

 

History

History
70 lines (47 loc) · 1.36 KB

2017-01-19-binding-objects-to-functions.md

File metadata and controls

70 lines (47 loc) · 1.36 KB
layout title tip-number tip-username tip-username-profile tip-tldr redirect_from categories
post
Binding objects to functions
61
loverajoel
Understanding how to use `Bind` method with objects and functions in JavaScript
/en/binding-objects-to-functions/
en
javascript

More than often, we need to bind an object to a function’s this object. JS uses the bind method when this is specified explicitly and we need to invoke desired method.

Bind syntax

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Parameters

thisArg

this parameter value to be passed to target function while calling the bound function.

arg1, arg2, ...

Prepended arguments to be passed to the bound function while invoking the target function.

Return value

A copy of the given function along with the specified this value and initial arguments.

Bind method in action in JS

const myCar = {
 brand: 'Ford',
 type: 'Sedan',
 color: 'Red'
};

const getBrand = function () {
 console.log(this.brand);
};

const getType = function () {
 console.log(this.type);
};

const getColor = function () {
 console.log(this.color);
};

getBrand(); // object not bind,undefined

getBrand(myCar); // object not bind,undefined

getType.bind(myCar)(); // Sedan

let boundGetColor = getColor.bind(myCar);
boundGetColor(); // Red