Function.prototype.my_bind = function(context) {
var args = Array.prototype.slice.call(arguments, 1);
var self = this;
return function () {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply(context, finalArgs);
}
};
测试:
function f(y, z){
return this.x + y + z;
}
var m = f.my_bind({x : 1}, 2);
var mm = f.bind({x : 1}, 2);
console.log(m(3));//6
console.log(mm(3));//6
这里解释一下Array.prototype.slice.call
,因为一些具有length属性的对象是没有有数组的splice方法的,但是它们又需要这个强大的切片功能,所以要靠原型继承来实现,这样对象就可以像数组一样来调用slice了。
参考博客:https://blog.csdn.net/qlwangcong518/article/details/86261597