Created
December 25, 2022 05:30
-
-
Save thmain/ca7b5d4ef2f826d7927f0a2dc40ec454 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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