Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Last active June 15, 2022 09:15
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yyx990803/6311083 to your computer and use it in GitHub Desktop.
Save yyx990803/6311083 to your computer and use it in GitHub Desktop.
implementing Function.prototype.bind
Function.prototype.bind = function (context) {
if (typeof this !== 'function') {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var fn = this, // the function to bind
slice = Array.prototype.slice // cache slice method
args = slice.call(arguments, 1), // get the array of addtional arguments (to be curried)
noop = function () {}, // the intermediate function to serve as a prototype chain connector
// (assuming we don't have Object.create() here)
bound = function () {
var ctx = this instanceof noop && context
? this
: context
return fn.apply(ctx, args.concat(slice.call(arguments)))
}
// inherit the prototype of the to-be-bound function
noop.prototype = fn.prototype
bound.prototype = new noop()
return bound
}
function Test (arg) {
return this.value + arg
}
var obj = {
value: 123
},
test = Test.bind(obj)
console.log(test(345) === (123 + 345))
@stavalfi
Copy link

stavalfi commented Sep 6, 2019

different approach:

Function.prototype.bind = function bind(funcThis, ...params) {
  if (typeof this !== 'function') {
    throw new Error("can't run bind function on non-functions")
  }
  const newFunc = (...aditionalParams) => this.call(funcThis, ...params, ...aditionalParams)
  newFunc.bind = (...aditionalParams) => bind.call(this, funcThis, ...params, ...aditionalParams.slice(1))
  return newFunc
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment