Skip to content

Latest commit

 

History

History
47 lines (39 loc) · 1.68 KB

bind.md

File metadata and controls

47 lines (39 loc) · 1.68 KB
title tags author_title author_url author_image_url description image
bind
function
object
intermediate
Deepak Vishwakarma
Implementation of "bind" in typescript, javascript and deno.

TS JS Deno

Creates a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.

Return a function that uses Function.prototype.apply() to apply the given context to fn. Use Array.prototype.concat() to prepend any additional supplied parameters to the arguments.

export const bind =
  <T = any>(fn: (...args: any[]) => any, context: T, ...boundArgs: any[]) =>
  (...args: any[]) =>
    fn.apply(context, [...boundArgs, ...args]);

TS: You need to bind this type

const freddy = { user: "fred" };
function greet(this: typeof freddy, greeting: string, punctuation: string) {
  return greeting + " " + this.user + punctuation;
}
const freddyBound = bind(greet, freddy);
console.log(freddyBound("hi", "!")); // 'hi fred!'

JS Version:

function greet(greeting, punctuation) {
  return greeting + " " + this.user + punctuation;
}
const freddy = { user: "fred" };
const freddyBound = bind(greet, freddy);
console.log(freddyBound("hi", "!")); // 'hi fred!'