继承

2018-01-11  本文已影响6人  魂之挽歌w

1.构造函数实现继承,具体:在构造函数中,使用apply()和call()方法实现继承

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实现继承

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中,我们要避免发生这样直接的

3.利用class实现继承

在ES6中可以利用Class通过extends关键字实现继承,这比之前的通过修改原型链实现继承的方式要方便得多了。尤其是做Java,Android开发的童鞋看到Class时倍感亲切,但是稍微遗憾的是目前不少浏览器(包括我目前使用的谷歌浏览器)对于ES6的Class兼容得不是很好。不过,也不用担心,我相信过不了多久主流的浏览器都会很好地支持Class


鸭式辨型:

     我们想在printStudentMessage函数中打印Student类型的对象的信息。但是由于JavaScript是弱语言,所以不能确保传递给printStudentMessage( )方法的参数必是Student类型的。为了程序的严谨和避免不必要的麻烦,我们可对传入的参数进行辨识!

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("传入参数不是Student");

            }

        }

        var stu=new Student(9527,"周星星");

        printStudentMessage(stu);

上一篇 下一篇

猜你喜欢

热点阅读