Skip to content

Instantly share code, notes, and snippets.

@thmain
Created December 25, 2022 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/ca7b5d4ef2f826d7927f0a2dc40ec454 to your computer and use it in GitHub Desktop.
Save thmain/ca7b5d4ef2f826d7927f0a2dc40ec454 to your computer and use it in GitHub Desktop.
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)
}
}
// Ex 1: Create a function with a preset leading argument
function list() {
// arguments is an array-like object. convert arguments to an array.
return Array.prototype.slice.call(arguments);
}
console.log( list(1, 2, 3) ) // [1, 2, 3]
var leadingThirtysevenList = list.bind1(null, 37)
console.log( leadingThirtysevenList() ) // [37]
console.log( leadingThirtysevenList(1, 2, 3) ) // [37, 1, 2, 3]
// Ex 2: Changing the scope of `this`
var foo = {
x: 3
}
function bar (){
console.log(this.x)
}
var boundFunc = bar.bind1(foo)
boundFunc() // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment