call 方法可以用來代替另一個物件呼叫一個方法,它能將函式的物件上下文從初始上下文改為由 thisObj 指定的新物件。
call 方法
呼叫一個物件的方法,以另一個物件取代當前物件。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
參數1:thisObj
可選項。將被作為當前物件的物件。
參數2:arg1, arg2, , argN
可選項。將被傳遞給方法的參數序列。
說明:
call 方法可以用來代替另一個物件呼叫一個方法,並將函式的物件上下文從初始上下文改為由 thisObj 指定的新物件。若沒有提供 thisObj 參數,則以 Global 物件作為 thisObj。
說實話,第一次看這段定義我也沒看懂,那就繼續往下看吧。
call 方法在 JS 繼承中經常出現,也一直搞不懂它到底是什麼,看看這段程式碼:
01.function Person(name,age){
02.
this.name = name;
03.
this.age=age;
04.
this.alertName = function(){
05.
alert(this.name);
06.
}
07.
this.alertAge = function(){
08.
alert(this.age);
09.
}
10.
}
11.
12.
function webDever(name,age,sex){
13.
Person.call(this,name,age);
14.
this.sex=sex;
15.
this.alertSex = function(){
16.
alert(this.sex);
17.
}
18.
}
19.
var test= new webDever("愚人碼頭",28,"男");
20.
test.alertName();//愚人碼頭
21.
test.alertAge();//28
22.
test.alertSex();//男
這樣 webDever 類就繼承了 Person。Person.call(this,name,age) 的意思就是使用 Person 物件代替 this 物件,那麼 webDever 中不就有了 Person 的所有屬性和方法了嗎?於是 test 物件就能直接呼叫 Person 的方法與屬性。
說得再明白一點,就是相當於把 webDever 中的 Person.call(this,name,age) 這段程式碼,替換成 Person 類的:
1.this.name = name;
2.
this.age=age;
3.
this.alertName = function(){
4.
alert(this.name);
5.
}
6.
this.alertAge = function(){
7.
alert(this.age);
8.
}
這樣 webDever 類就相當於:
01.
function webDever(name,age,sex){
02.
this.name = name;
03.
this.age=age;
04.
this.alertName = function(){
05.
alert(this.name);
06.
}
07.
this.alertAge = function(){
08.
alert(this.age);
09.
}
10.
11.
this.sex=sex;
12.
this.alertSex = function(){
13.
alert(this.sex);
14.
}
15.
}
16.
var test= new webDever("愚人碼頭",28,"男");
17.
test.alertName();//愚人碼頭
18.
test.alertAge();//28
19.
test.alertSex();//男
不知道這樣理解對不對?還望大家指正。
留一個問題:假設 webDever 類只想繼承 Person 類中的 alertName 方法,這樣可以嗎?程式碼該怎麼寫?