call 與 apply 是 JavaScript 中改變函式 this 指向的兩個方法,兩者差別只在參數的傳遞方式:call 逐一列出參數,apply 則以陣列一次傳入。靈活運用它們,還能實現類似物件導向的繼承效果。
以下範例先示範用 call 呼叫函式並指定 this,接著示範如何在子類別建構子中透過 call 呼叫父類別建構子,完成屬性繼承:
/* 矩形 */
function Rectangle(len, width) {
this.len = len;
this.width = width;
}
/* 相乘 */
function multiply(a, b) { return a * b; }
// 建立矩形實例並求面積
var rectangle = new Rectangle(15, 30);
// 使用 call,把 rectangle 作為 this 傳入
var proportion = multiply.call(rectangle, rectangle.len, rectangle.width);
// 以 apply 改寫則為:
// var proportion = multiply.apply(rectangle, [rectangle.len, rectangle.width]);
document.write("矩形的面積是:" + proportion);
document.write("<br/>");
document.write("/***********************分割線****************************/<br/>");
/* 以 call 實作繼承 */
function Persion(name) {
this.name = name;
this.sayHello = function () { return "hello," + this.name; };
}
function Student(name, sex, school) {
Persion.call(this, name); // 關鍵:呼叫父類別建構子並沿用 this
this.sex = sex;
this.school = school;
this.mySex = function () { return this.sex; };
this.mySchool = function () { return this.school; };
}
var stu = new Student('fengjx', '男', '廣西機電職業技術學院');
document.write("stu sayHello:" + stu.sayHello());
document.write("<br/>");
document.write("stu sex is:" + stu.mySex());
document.write("<br/>");
document.write("stu school is :" + stu.mySchool());
document.write("<br/>");
重點在於 Persion.call(this, name) 這一行:它把 Student 實例的 this 傳入父建構子,讓子物件也擁有父類別的屬性與方法。這樣一來,Student 的實例就能直接使用 sayHello 方法,達到了屬性繼承的效果。
