JS: Function.prototype.bind

By Xah Lee. Date: . Last updated: .

f.bind(obj) → returns a function such that it has the same behavior as f except f's this value is always obj.

[see JS: “this” Binding]

f.bind(obj, args …) → the new function will always be given the arguments args.

// example of using Function.prototype.bind

// object with 1 property ff.
const aa = { "ff":function () { return this;} };

// new object bb
const bb = {"b":2};

// create a new function, that is ff with thisBinding of bb
const gg = aa.ff.bind(bb);

console.log( gg() ); // { b: 2}

Example of using Function.prototype.bind with default argument:

// Example of using Function.prototype.bind with default argument

function ff(x) { this["p"] = x; };

const bb = {"b":2};

// create a new function
// with default ThisBinding and a default arg
const gg = ff.bind(bb,7);

// call gg
gg();
// note, no args are given.

console.log( bb ); // { b: 2, p: 7 }

Reference

ECMAScript 2015 §Fundamental Objects#sec-function.prototype.bind

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon