JavaScript: Function.prototype.bind
f.bind(obj)
- Return a function such that it has the same behavior as f except f's this Binding is always obj.
f.bind(obj, args etc)
- 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 }