平常在开发中使用bind大多是为了在函数执行时来改变函数体中this的指向的。但很少有人会去关注它具体内部是怎么实现的,现在就从腾讯课堂上抄来一段代码,这个只是模拟实现原理,实质上我们并不知道真实是怎么实现的。先放到这里,后面慢慢研究……
Function.prototype.bindFn = function (target) { var that = this; var args = [].slice.call(arguments, 1); var temp = function () {}; var res = function () { var arg = [].slice.call(arguments, 0); return that.apply(this instanceof temp ? this : (target || window), args.concat(arg)); } temp.prototype = that.prototype; res.prototype = new temp(); return res; }
以上代码中在Function原型上挂了一个bindFn方法,在定义函数的时候只要将该方法跟到函数后面,里面的第一个参数将会取代该函数体中的this。
发表评论