最近在看jQuery源碼,裏面好多地方用到了call(),apply()一直不是很理解這兩個函數,今天花了點時間瞭解了一下,只是瞭解了一些皮毛
apply和call()的區別就是裏面的參數
apply(thisObj,[arguments])
call(thisObj,arr1,arr2...)
根據網上說的,這兩個函數的實質就是改版this的指向,例
function add(a, b){
console.info(this);
this.a=a;
this.b=b;
alert(this.a);
}
function sub(a, b){
console.info(this);
this.a=a;
this.b=b;
alert(this.a);
}
add.call(sub, 'sub', 2);//提示sub
sub.apply(add, ['add', 2]);//提示add
thisObj也可以是一個對象,比如
</pre></p><p><pre name="code" class="javascript">function test(name){
this.name=name;
}
test.prototype.sayName=function(){
alert(this.name);
}
var t=new test('ttt');
t.sayName();
var a={'name':'tom'};
t.sayName.call(a);//提示tom
好吧,組織不好語言,瞭解的也不多,第一篇文章就這樣吧!繼續努力!!!