call,apply,bind的区别
这三个函数的左右都是为了指定当前的this。
不同点:
- call,apply 两者都是对函数的直接调用,bind的返回值仍然是一个函数。
举例:a.call(b) 或者 a.apply(b) 而bind需要 a.bind(b)()这样才能执行 - call和apply的传参方式不同,第一个值都是this的指向,第二个举例
1 | a.call(b, 参数1,参数2,参数3) |
以上就是三者的差别。
接下来我们实现他们的功能函数。
call:
call的传入参数是(ctx,…[])
1
2
3
4
5
6
7
8
9
10
11Function.prototype.mycall = funciton (ctx) {
if (typeof this != "function") {
throw new TypeError('error');
}
ctx = ctx || window;
ctx.fn = this;
var args = ...arguments.splice(1);
var result = ctx.fn(args);
delete ctx.fn;
return result;
}apply:
apply的传入参数跟call不同,第二个参数是数组。
1 | Function.prototype.myapply = funciton (ctx) { |
- bind 返回的是个函数
bind 返回的是个函数,同样可以执行传参 ,我们可以用myapply实现
1 | Funtion.prototype.myBind = function(ctx,...args1){ |