Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Last active Jul 15, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@stavalfi 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