1.Function.prototype.myBind():bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
2.Array.prototype.slice.call(arguments):能将具有length属性的对象转成数组。
3.array.shift():删除数组中的第一个元素(red),并返回被删除的元素:
<script>
function fn(a, b, c, d) {
console.log(this);
console.log(a, b, c, d);
return "this is return"
}
// const cb = fn.bind({ x: 100 }, 1, 2, 3);
// console.log(cb());
// 手写bind
Function.prototype.myBind = function () {
const fn = this;
// { x: 100 }, [1, 2, 3]
const arg = Array.prototype.slice.call(arguments);
const _this = arg.shift();
return function () {
return fn.apply(_this, arg);
}
}
const cb = fn.myBind({ x: 200 }, 1, 2, 3, 4);
console.log(cb());
</script>