本文整理 call 與 apply 兩個方法的用法,並示範如何藉由 call 完成 JavaScript 的「類別繼承」。
兩者的作用完全相同:把函式以指定的 this 呼叫。差別只在參數傳遞形式——call 逐一列舉參數,apply 則接收一個陣列。
/* * 矩形 */ function Rectangle(len,width) { this.len = len; this.width = width; } /* * 乘以 */ function multiply(a,b) { return a * b; } // 矩形實例 var rectangle = new Rectangle(15, 30); //求矩形面積 var proportion = multiply.call(rectangle,rectangle.len, rectangle.width); // 等價於call //var proportion = multiply.apply(rectangle,[rectangle.len, rectangle.width]); document.write("矩形的面積是:"+proportion); document.write("<br/>"); document.write("/***********************分割線********************************/<br/>"); // 實現繼承 function Persion(name) { this.name = name; this.sayHello = function () { return "hello,"+this.name; } } function Student(name,sex,school) { Persion.call(this,name); 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 實例時,等於把父函式 Persion 借過來、以子物件作為 this 執行一次,於是父類別的屬性與方法就被複製到新的子物件上。這種做法在業界常被稱為「借用建構子」。
要注意的是,這種方式只繼承了父類別「自己」的屬性與方法,掛在 prototype 上的成員並不會被複製;若需要完整繼承,通常還得搭配原型鏈銜接。
演示圖:
以上就是本文的全部內容,希望大家能夠喜歡。