javascript面向对象中继承实现的几种方式

1.原型链继承:

    function teacher(name){  
        this.name = name;  
    }  
    teacher.prototype.sayName = function(){  
        alert(this.name);
    }   
      
    function student(name){  
        this.name = name;  
    }  
student.prototype = new teacher() var student1 = new student("xiaolan"); student1.sayName(); // name is xiaolan

 2.组合式继承:是开发中最长用的

function Person  (name) {
             this.name = name;          
         };

         Person.prototype.getName = function () {
             return this.name;
         };

        function Parent (age) {
            Person.call(this,'老明');  //这一步很关键
            this.age = age;
        };

        Parent.prototype = new Person('老明');  //这一步也很关键
        var result = new Parent(24);
        console.log(result.name);    //老明
        console.log(result.getName());  //老明
        console.log(result.age);    //24

        var result1 = new Parent(25);   //通过借用构造函数都有自己的属性,通过原型享用公共的方法
        console.log(result1.name);  //老明
 

 3.call和applay继承:

 

function teacher(name){
    this.name=name;
    this.sayName=function(){
        alert(this.name);
    }
}

function student(age){
        teacher.call(this,"小明");
        this.age=age;
}
    var ss=new student("30");
    ss.sayName();//小明
    alert(ss.age);//30

 

转载于:https://www.cnblogs.com/zhaoxinmei-123/p/9021226.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值