
用法与结构:
- 结构 call(s,1,2,...) ,apply(s,array)
- 作用:这两东东 主要是 改变this指向 还有继承方法
1、改变函数体内部 this 的指向 2、实现继承 - 相同点
第一个参数都是this要指向的对象。 - 不同点
剩余的参数传入形式不同。 1.call的后续参数可以是任何类型 2.apply最多只能有两个参数
ヾ(◍°∇°◍)ノ゙
call()
例子:
var obj = {"s":2};
var addCall = function(a,b,c){
console.log(this) //打印this的指向
return this.s + a + b + c;
};
var result = addCall.call(obj,1,2,3); //调用这个方法
console.log(result);// {s:2} 可以看出this指向是obj 2+1+2+3 = 8
1.在这里,实际可以看成 var result = obj.addCall(1,2,3),return obj.s+a+b+c 当然,可以这
么理解,
但是,你可千万别这么写 , 这里只是 ▊ 方便理解 ▋。
2.当然,你也可以理解为 addCall.call(obj,1,2,3)
里面的 obj 继承了addCall 的方法 。
3.或者 addCall.call(obj,1,2,3)里面的obj 调用了addCall方法。
apply()
例子:
var obj = {"s":2};
var addApply = function(a,b,c){
console.log(this) //打印this的指向
return this.s + a + b + c;
};
var result = addApply.apply(obj,[1,2,3]); //调用这个方法
console.log(result);// {s:2} 可以看出this指向是obj 2+1+2+3 = 8
基本上和 call 差不多 也就是结构上的不同
ps: 有错误的地方可以告诉我 之前发的反响不好 割了