JavaScript 手写模拟bind函数
-
关于bind()函数的解释
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
关于arguments的解释
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments
// 使用Function.prototype.myBind 从Function原型链中定义Mybind Function.prototype.myBind = function (){ // 将参数拆解为数组 const args = [].slice.call(arguments) // 获取要改变的this, 数组的第一项 const th = args.shift() // 获取调用者的this, 比如这里fn1.myBind this就是fn1 const self = this // 返回一个函数, return function (){ return self.apply(th, args) } } function fn1 (a,b,c){ console.log(this) console.log(a,b,c) return "这是fn1" } const fn2 = fn1.myBind({x:"看到我说明this被改变"}, 1, 2, 3) const res = fn2() console.log(res)
更多推荐主题
-
JavaScript 闭包
综合讨论 • • icewing