兼容低版本浏览器的bind方法的代码实现

高版本的firefox,chrome及ie10以上的浏览器实现了Function.prototype.bind方法,bind方法调用语法为:
functionObj.bind(thisArg[, arg1[, arg2[, ...]]])
使用范例参考如下:

function move(x, y) {
    this.x += x;
    this.y += y;
}
var point = {x:1, y:2};
var pointmove = move.bind(point, 2, 2);
pointmove(); // {x:3, y:4}

但是低版本浏览器中并未提供该方法,请给出兼容低版本浏览器的bind方法的代码实现。

实现思路

  • 回顾Function.prototype.bind用法:通过参数指定函数调用者和函数参数并返回该函数引用,可知
  • 判断浏览器是否兼容,不兼容就move添加一个bind的方法,让其能够调用move.bind
 Function.prototype.bind
  • 将参数转换为数组保存
  • 同时将数组返回

var _self = this, args = arguments;
return function() {
_self.apply(obj, Array.prototype.slice.call(args, 1));
}

* 所以可得

Function.prototype.bind= function(obj){
var _self = this, args = arguments;
return function() {
_self.apply(obj, Array.prototype.slice.call(args, 1));
}
}

* 在解题的过程中,有些知识点掌握不熟练导致花了很多时间理解,例如原型链,构造函数,构造方法等等,搜寻网上的相关资料,有一个关于prototype的解析不错:[Prototype源码浅析——Function.prototype部分(一)](http://www.cnblogs.com/xesam/archive/2011/12/17/2290797.html)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容