標籤:AC prototype var 輸出 cal asc class 實現繼承 parent
一、原型鏈繼承
function Parent(){} function Child(){} Child.prototype = new Parent();
通過對象child的prototype屬性指向父物件parent的執行個體,使child對象的執行個體通過原型鏈訪問到父物件構造所定義的屬性、方法等。
二、使用apply、call方法
js中call和apply都可以實現繼承,唯一的一點參數不同,func.call(func1,var1,var2,var3)對應的apply寫法為:func.apply(func1,[var1,var2,var3])。
相同點:第一個參數this都一樣,指當前對象。
不同點,第二參數不一樣,call是一個個的參數列表,apply是一個數組(arguments也可以)
<script type="text/javascript"> function Person(name,age,love){ this.name=name; this.age=age; this.love=love; this.say=function say(){ alert("姓名:"+name); } } //call方式 function student(name,age){ Person.call(this,name,age); } //apply方式 function teacher(name,love){ Person.apply(this,[name,love]); //Person.apply(this,arguments); //跟上句一樣的效果,arguments } //call與aplly的異同: //1,第一個參數this都一樣,指當前對象 //2,第二個參數不一樣:call的是一個個的參數列表;apply的是一個數組(arguments也可以) var per=new Person("武鳳樓",25,"魏熒屏"); //輸出:“武鳳樓” per.say(); var stu=new student("曹玉",18);//輸出:“曹玉” stu.say(); var tea=new teacher("秦傑",16);//輸出:“秦傑” tea.say(); </script>
三、對象執行個體間的繼承
原文來自:http://www.jb51.net/article/20431.htm
javascript實現繼承的三種方式