javascript繼承方法有:1、使用call()方法,可以編寫能夠在不同對(duì)象上使用的方法;2、apply()方法,語法“apply(用作 this 的對(duì)象,要傳遞給函數(shù)的參數(shù)的數(shù)組)”。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
1、call() 方法
call() 方法是與經(jīng)典的對(duì)象冒充方法最相似的方法。它的第一個(gè)參數(shù)用作 this 的對(duì)象。其他參數(shù)都直接傳遞給函數(shù)自身
function Huster(name,idNum,college) { this.name = name; this.idNum = idNum; this.college = college; this.course = new Array(); this.addCourse = function(course)//這個(gè)方法不能用prototype來定義,如果用的話,子類無法繼承該方法 { //用原型prototype定義的方法可以用原型鏈來繼承,call()方法和apply()方法都無法繼承 this.course.push(course); console.log(this.course); }; } function Autoer(name,idNum) { this.college = ‘自動(dòng)化‘; Huster.call(this,name,idNum,this.college);//Autoer使用call()方法來繼承 Huster if (typeof Autoer._initialized == "undefined") { Autoer.prototype.sayHobby = function() //自己的方法可以用原型鏈prototype定義 { alert(this.college+‘人喜歡擼代碼!‘); }; Autoer._initialized = true; } } var autoer1 = new Autoer(‘偶人兒‘,‘U123456789‘); //聲明一個(gè)實(shí)例autoer1 console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course); autoer1.addCourse(‘logistics‘);//調(diào)用Huster的方法 autoer1.sayHobby(); //調(diào)用自身的方法
2、apply() 方法
apply() 方法與call()方法幾乎一樣,唯一的區(qū)別就是apply()方法只有兩個(gè)參數(shù),第一個(gè)用作 this 的對(duì)象,第二個(gè)是要傳遞給函數(shù)的參數(shù)的數(shù)組。也就是說apply()方法把call()方法的若干個(gè)參數(shù)放到一個(gè)數(shù)組里,傳遞給父類
function Huster(name,idNum,college){ this.name = name; this.idNum = idNum; this.college = college; this.course = new Array(); this.addCourse = function(course)//這個(gè)方法不能用prototype來定義,如果用的話,子類無法繼承該方法 { //用原型prototype定義的方法可以用原型鏈來繼承,call()方法和apply()方法都無法繼承 this.course.push(course); console.log(this.course); }; } function Autoer(name,idNum) { this.college = ‘自動(dòng)化‘; Huster.apply(this,new Array(name,idNum,this.college));//Autoer使用apply()方法來繼承 Huster if (typeof Autoer._initialized == "undefined") { Autoer.prototype.sayHobby = function() //自己的方法可以用原型鏈prototype定義 { alert(this.college+‘人喜歡擼代碼!‘); }; Autoer._initialized = true; } } var autoer1 = new Autoer(‘偶人兒‘,‘U123456789‘); //聲明一個(gè)實(shí)例autoer1 console.log(autoer1.name,autoer1.idNum,autoer1.college,autoer1.course); autoer1.addCourse(‘logistics‘);//調(diào)用Huster的方法 autoer1.sayHobby(); //調(diào)用自身的方法
【推薦學(xué)習(xí):javascript視頻教程】