Last active
June 15, 2022 09:15
-
-
Save yyx990803/6311083 to your computer and use it in GitHub Desktop.
implementing Function.prototype.bind
This file contains hidden or 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.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 | |
} |
This file contains hidden or 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 Test (arg) { | |
return this.value + arg | |
} | |
var obj = { | |
value: 123 | |
}, | |
test = Test.bind(obj) | |
console.log(test(345) === (123 + 345)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
different approach: