1.構(gòu)造函數(shù)實現(xiàn)繼承棋枕,具體:在構(gòu)造函數(shù)中敷鸦,使用apply()和call()方法實現(xiàn)繼承
function Person(){
? ? this.species="human";
? ? this.eat=function (){
? ? document.writeln(this.name+"吃飯");
}
}
function Student(school,name,age){
Person.apply(this,arguments);
this.name=name;
this.age=age;
this.school=school;
this.study=function study(){
document.writeln(this.name+"學習");}
}
? ?var s=new Student();
? ? s.name="吳海忠";
? ? s.age=23;
? ? s.school="zjlg";
? ? document.writeln(s.school);
? ? document.writeln(s.species);
? ? ? s.study();
? ? ? ?s.eat();
2.prototype實現(xiàn)繼承
function Person1(){};
Person1.prototype.species="human";
Person1.prototype.eat=function (){
document.writeln("吃飯");}
function Teacher(name,age){
this.age=age;
this.name=name;
this.teach=function(){
document.writeln(this.name+"教學");
}
}
var nullFunction=function (){};
nullFunction.prototype=Person1.prototype;
Teacher.prototype=new nullFunction();
Teacher.prototype.constructor=Teacher;//這么做之后Student的prototype的constructor也變成了Person的prototype的constructor息楔!
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //所以,要將Student的prototype的constructor重新設置為Student
var teacher=new Teacher("whz",44);
document.writeln(teacher.species);
teacher.teach();
teacher.eat();
//注意:用一個中間對象扒披,不能直接把兩個prototype相等(Teacher.prototype=Person.prototype)值依,因為這樣會導致Person.prototype和Teacher.prototype指向同一個對象,
//這樣所有對Teacher.prototype的修改都會映射到person.prototype中谎碍,我們要避免發(fā)生這樣直接的
3.利用class實現(xiàn)繼承
在ES6中可以利用Class通過extends關鍵字實現(xiàn)繼承鳞滨,這比之前的通過修改原型鏈實現(xiàn)繼承的方式要方便得多了。尤其是做Java蟆淀,Android開發(fā)的童鞋看到Class時倍感親切拯啦,但是稍微遺憾的是目前不少瀏覽器(包括我目前使用的谷歌瀏覽器)對于ES6的Class兼容得不是很好。不過熔任,也不用擔心褒链,我相信過不了多久主流的瀏覽器都會很好地支持Class
鴨式辨型:
? ? ?我們想在printStudentMessage函數(shù)中打印Student類型的對象的信息。但是由于JavaScript是弱語言疑苔,所以不能確保傳遞給printStudentMessage( )方法的參數(shù)必是Student類型的甫匹。為了程序的嚴謹和避免不必要的麻煩,我們可對傳入的參數(shù)進行辨識!
function ?Student(id,name){?
? ? ? ? ? ?this.id=id;
? ? ? ? ? ? this.name=name;
? ? ? ? }
? ? ? ? functionprintStudentMessage(s){? ? ??
? ? ? if(typeof s=="object" && typeof s.id=="number"){
? ? ? ? ? ? ? ? document.writeln("id="+s.id+",name="+s.name);
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? document.writeln("傳入?yún)?shù)不是Student");
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? var stu=new Student(9527,"周星星");
? ? ? ? printStudentMessage(stu);