实现bind函数之前,首先了解bind函数的特性:
- 预置参数;
- 改变原函数的this指向;
- 返回一个函数;
- 返回函数的返回值类型与原函数一致,即原函数有返回值,bind后的函数也要有返回值;
- 返回的函数可以作为构造函数,且保留原函数的原型链;
实现前4个特性很简单:
Function.prototype.newBind = function (target) {
const that= this; // 存储原函数地址
const bindArguments = Array.prototype.slice.call(arguments, 1); //预留参数
// 返回一个函数
return function () {
const curArguments= Array.prototype.slice.call(arguments,0);
const allArguments = bindArguments.concat(curArguments); //合并参数
return that.apply(target, allArguments); // 返回执行后的值,如果有
}
}
但是满足不了可以做构造函数的特性,构造函数的this必须是指向 新创建的实例的,这时候bind指定的this应该失效。
例如: 使用bind 返回的函数构造出来的实例是不符合期望的。
function Test(a,b) {
this.total = a +b;
}
const target = {total:0};
const