-
Inheritance in Javascript
- <script language="javascript" type="text/javascript">
- <!--
- function SuperClass(){
- //attach method supperTest
- this.superTest=superTest;
- }
- function subClass(){
- this.inheritFrom = SuperClass;
- this.inheritFrom();
- this.subTest=subTest;// subTest
- }
- function superTest() {
- return "superTest";
- }
- function subTest() {
- return "subTest";
- }
- //use example
- var obj =new subClass();
- alert(obj.subTest());
- alert(obj.superTest());
- //another way of inheritance
- Person=function(name)
- {
- this.name=name
- };
- Person.prototype={
- Speak:function(msg){
- alert(this.name + ":" + msg);
- },
- Walk:function(){
- alert(this.name + ":" + "walk");
- }
- };
- //test person
- var p=new Person("person");
- p.Speak("GC");
- p.Walk();
- //student derive from class person
- Student =function(){
- };
- //inherit from Person
- Student.prototype=new Person();
- //add methods
- Student.prototype.Study=function(){
- alert("Benny studies!");
- }
- //test student
- var s=new Student();
- s.name="benny.s.xu";
- s.Walk();
- s.Speak("newegg");
- //override speak method
- Student.prototype.Speak=function(){
- alert("override speak method");
- }
- s.Speak();
- -->
- </script>