JavaScript: Function.prototype.bind

By Xah Lee. Date: . Last updated: .
f.bind(thisBinding)
Return a function such that it has the same behavior as f except f's this Binding is always thisBinding.
// 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() === bb);
f.bind(thisBinding, arg1, arg2, etc)
the new function will always be given the arguments args.
// 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, no args are given
gg();

// now gg has property key p and value 7
console.log(bb.p === 7);

JavaScript: Apply Function

BUY ΣJS JavaScript in Depth