標籤:
一、apply介紹
1、apply是前端javascript方法預設內建的方法,這要的用法是替換掉當前執行的方法的this對象,從而實現繼承,或者修改方法內部使用到this對象;
這次先說繼承:
例如:
首先,在test方法裡邊聲明兩個方法,add,sub:
function test(){
this.add=function(a,b){
return a+b;
}
this.sub=function(a,b){
return a-b;
}
}
然後,我們接著定義一個方法test2:
function test2(){
test.apply(this);
}
接著,我們產生執行個體t2,執行個體化過程中test2成為t2的建構函式,此時test2方法裡頭的this對象是指t2的;
var t2=new test2();
那麼現在,我們可以測試t2:
t2.add(2,1);
t2.sub(3,2);
結果是不是很神奇。
2、apply有一個重要的特性就是改變當前執行的方法的this對象;
例如:
<input type=‘file‘ id=‘test‘/>
首先我們定義一個檢測檔案尾碼名的方法,此時的this對象是指向window,我們看下邊的兩個測試例子:
function checkFileType(){
var _value=this.value;
var pattern=/\.[a-zA-Z]$/;
var result=pattern.exec(_value);
if(result!=null)
console.log(result);
else
console.log(‘not find‘);
}
那麼現在我們就使用apply:
$("#test").click(function(){
checkFileType();
});
$("#test").click(function(){
checkFileType.apply(this);
});
此時我們會發現,第一個打出的是not find,第二個正確的列印出了附件尾碼名。
到此就介紹完了apply兩個核心用法,繼承與改變當前執行方法的this對象。
二、prototype特性
prototype是前端方法預設內建的屬性,主要的用處是在執行個體之間共用方法;例如:
function test(){};
test.prototype.add=function(a,b){
return a+b;
}
test.prototype.sub=function(a,b){
return a-b;
}
var t1=new test();
var t2=new test();
t1.add(2,1);
t2.add(3,2);
t1.sub(2,1);
t2.sub(3,2);
從上面的例子,我們可以看到t1,t2兩個執行個體都可以調用到add,sub這兩個方法;
三、this對象
由於javascript是解釋型語言,所以this只有在執行中才能確定。
在實踐中我們可以總結出this的規律,this指向當前方法所屬的執行個體:
1、例如:function test(){
console.log(this);}
test();
此時我們發現this指向window,因為test()是定義在window裡邊的方法,即我們可以這樣調用window.test(),也就是說test是window的方法。
2、test.prototype.add=function(){
console.log(this);}
var tt=new test();
tt.add();
此時,我們定義了一個執行個體tt,add是執行個體tt的一個方法,我們會發現this指向tt。
3、結合juqery使用
我們常常見到:$("#xx").click(function(){
console.log(this);
});
此時this是指向("#xx")執行個體的,有興趣可以抽出原始碼看看()是jquery的一個Factory 方法,返回的是一個執行個體。
上面的例子,click方法屬於("#xx")執行個體的因此,click內部的this指向("#xx")。當click調用回掉方法時,會使用fn.apply(this),因此我們在回掉方法列印出來的this是指向$("#xx")的。
四、arguments
在javascript裡邊arguments是一個數組,用來接收當前方法傳入的參數。
javascript apply,prototype,this,argument