JavaScript面向對象---繼承
javaScript沒有集成的對象,所以采用下面三種方法模擬:
1、js原型實現繼承
function Person(name,age){ this.name=name; this.age=age; } Person.prototype.sayHello=function(){ document.write("使用原型得到Name:"+this.name+"</br>"); }//var per=new Person("zhangping","21"); //per.sayHello();
function Student(){} Student.prototype=new Person("zhangping","21"); var stu=new Student(); Student.prototype.gade="3"; Student.prototype.intr=function(){ document.write(this.gade); } stu.sayHello(); stu.intr(); / 2、構造函數實現繼承 / function Parent(name){ this.name=name; this.sayParent=function(){ document.write("Parent:"+this.name); } } function Child(name,age){ this.tempMethod=Parent; this.tempMethod(name); / this.age=age; this.sayParent=function(){ document.write("Child:"+this.name+"age:"+this.age); } / / } var parent=new Parent("zhangping"); parent.sayParent(); var child=new Child("xiaoguanxianfei","11"); child.sayParent();/
3、使用Call Applay實現繼承
function Person(name,age,love){ this.name=name; this.age=age; this.love=love; this.say=function say(){ document.write("姓名:"+name); } } function student(name,age){ Person.call(this,name,age); } function teacher(name,love){ Person.apply(this,[name,love]); } var per=new Person("zhangping","21","guanxianfei"); per.say(); var stu=new student("guanxianfei","22"); stu.say(); var tea=new teacher("xiaoguanxianfei","22"); tea.say();</pre>
來自: http://www.blogjava.net/17learning/archive/2011/12/15/366386.html </div>