By Noxxxx from https://www.noxxxx.com/?post_type=post&p=591
欢迎分享与聚合,尊重版权,可以联系授权
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数
首先 bind 不同于 call 和 apply 它不是调用后立即执行。
所以第一个关键点就是闭包。
Function.prototype.toBind = function (context) { var self = this; return function () { self.apply(context); } }
接下来处理传参。
Function.prototype.toBind = function (context) { var self = this; // 获取toBind函数从第二个参数到最后一个参数 var args = Array.prototype.slice.call(arguments, 1); return function () { // 这个时候的arguments是指bind返回的函数传入的参数 var bindArgs = Array.prototype.slice.call(arguments); self.apply(context, args.concat(bindArgs)); } }
下一步是使用 new 关键字的时候,提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。
Function.prototype.toBind = function (context) { var self = this; var args = Array.prototype.slice.call(arguments, 1); var fNOP = function () {}; var fBound = function () { var bindArgs = Array.prototype.slice.call(arguments); self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs)); } fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }
最后加上polyfill是的判断。
Function.prototype.bind = Function.prototype.bind || function () { };