使用js手动实现bind、call、apply功能
Function.prototype.mycall = function () { const [first, ...rest] = arguments; const ctx = first || window; ctx.func = this; const ret = ctx.func(...rest); delete ctx.func; return ret; };
Function.prototype.myApply = function() { const [first, rest = []] = arguments; const ctx = first || window; ctx.func = this; const ret = ctx.func(...rest); delete ctx.func; return ret; }
Function.prototype.myBind = function() { const [first, ...rest] = arguments; const ctx = first || window; ctx.func = this; return function() { // 这里不能使用 箭头函数 因为箭头函数没有自己的 arguments 这样设计是为了让参数明确化 return ctx.func(...rest, ...arguments); }; // 返回的是一个函数 }
function show(a, b) { return a + b; }
注意:箭头函数没有自己的 arguments,这样设置是为了让函数传递参数 明确化,而不是用使用 arguments来接收
bind函数 可以传递参数,传递的参数 在函数定义的时候 固定下来了,如果在调用函数的时候再次传递参数,那么传递的参数,会追加在 已经固定值的参数
的后面。 但是bind一般都是只传递一个参数改变this指向就够了。
绑定的函数不能再次使用apply和call来改变this