Skip to content

Instantly share code, notes, and snippets.

@dlucidone
Last active February 8, 2019 04:31
Show Gist options
  • Save dlucidone/f1062788fcac779564953c117b5d0a4c to your computer and use it in GitHub Desktop.
Save dlucidone/f1062788fcac779564953c117b5d0a4c to your computer and use it in GitHub Desktop.
JS Bind Implementation
Function.prototype.bind1 = function (scope) {
let fn = this
let prefixArgs = Array.prototype.slice.call(arguments, 1)
return function() {
let suffixArgs = Array.prototype.slice.call(arguments)
let args = prefixArgs.concat(suffixArgs)
return fn.apply(scope, args)
}
}
function sum() {
var _sum = 0
for (var i = 0; i < arguments.length ; i++) {
_sum += arguments[i];
}
return _sum;
}
var sum_plus_two = sum.bind1({},2);
console.log(sum_plus_two(5,7))
var module = {
x: 42,
getX: function() {
return this.x;
}
}
var unboundGetX = module.getX;
var boundGetX = unboundGetX.bind1(module);
console.log(boundGetX());
function list() {
return Array.prototype.slice.call(arguments);
}
function addArguments(arg1, arg2) {
return arg1 + arg2
}
var list1 = list(1, 2, 3); // [1, 2, 3]
var result1 = addArguments(1, 2); // 3
// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(null, 37);
// Create a function with a preset first argument.
var addThirtySeven = addArguments.bind(null, 37);
var list2 = leadingThirtysevenList();
// [37]
var list3 = leadingThirtysevenList(1, 2, 3);
// [37, 1, 2, 3]
var result2 = addThirtySeven(5);
// 37 + 5 = 42
var result3 = addThirtySeven(5, 10);
// 37 + 5 = 42 , second argument is ignored
console.log(list2);
console.log(list3)
console.log(result2);
console.log(result3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment