普通版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function.prototype.bind = Function.prototype.bind || function (context) {
var me = this;
//伪数组转换成数组,并且预存初始参数
var args = Array.prototype.slice.call(arguments, 1);
console.log(me)
console.log(args)
return function bound () {
//获取二次传入的参数
var innerArgs = Array.prototype.slice.call(arguments);
//拼为最终参数
var finalArgs = args.concat(innerArgs);
console.log(innerArgs)
console.log(finalArgs)
return me.apply(context, finalArgs);
}
}

能在构造函数场景下兼容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Function.prototype.bind = Function.prototype.bind || function (context) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var me = this;
var args = Array.prototype.slice.call(arguments, 1);
var F = function () {};
F.prototype = this.prototype;
var bound = function () {
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return me.apply(this instanceof F ? this : context || this, finalArgs);
}
bound.prototype = new F();
return bound;
}

bind的偏函数用法,可以用于预设参数

1
2
3
4
5
6
7
8
9
10
11
12
13
function list(){
return Array.prototype.slice.call(arguments)
}

function addAuguments(arg1,arg2){
return arg1+arg2
}

let listRe = list.bind(null,37)
let addRe = addAuguments.bind(null,37)

console.log(listRe(12,54))//[ 37, 12, 54 ]
console.log(addRe(12,54))//49