Skip to content

Instantly share code, notes, and snippets.

@ericboy0224
Forked from yyx990803/bind.js
Last active June 15, 2022 09:40
Show Gist options
  • Save ericboy0224/251c760e745cf8b55a97cd3523ba5712 to your computer and use it in GitHub Desktop.
Save ericboy0224/251c760e745cf8b55a97cd3523ba5712 to your computer and use it in GitHub Desktop.
implementing Function.prototype.bind
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, // 這個 this 代表著被套用 bind 的 function (如 func.bind(this) 那麼 this 就是回傳那個 func)
slice = Array.prototype.slice // 暫存 slice 方法
args = slice.call(arguments, 1), // 這邊 call slice 帶入第一次 bind 的 arguments,並將執行環境以外的參數取下
noop = function () {}, // 這個中繼 function 用來提供 prototype chain 連接,假設沒有 Object.create()
bound = function () {
var ctx = this instanceof noop && context
? this
: context
return fn.apply(ctx, args.concat(slice.call(arguments)))
}
// 繼承被綁 function 的原型鏈
noop.prototype = fn.prototype
bound.prototype = new noop()
return bound
}
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