javascript继承

//原型继承
        /*定义一个人类*/
        function Person(name){
                this.property = 1;
        }        
        //声明父类方法
        Person.prototype.getPersonValue = function(){
                return this.property;
        }
        //声明子类构造函数
        function Student(){
                this.subproperty = 2;
        }
        //声明子类方法
        Student.prototype.getStudentValue = function(){
                return  this.subproperty;
        }
        Student.prototype = new Person("chentao");
        Student.prototype.constructor = Student;
        var studentIns = new Student();
        console.log(studentIns.getPersonValue());
    原型继承是有缺陷的,主要有两个问题;
    一. 包含引用类型值的原型,会被所有实例共享。
    function Person(){}
    Person.prototype = {
      constructor : Person,
      friends : ["greg","jack"]
    }
    var person1 = new Person();
    var person2 = new Person();
    person1.friends.push("tom");
    console.log(person2.friends);
    可以看到person2的实例中多了一个'tom',这并不是我们想要的.
    二. 创建子类型的实例时,不能向超类型的构造函数中传递参数。
        原型链的继承,直接将子类原型指向超类的实例,这时候可以向超类传递参数。
        但是当子类创建实例的时候,只能向子类的构造函数传递参数,而不能向超类的构造函数传递参数。    
//构造函数继承
        function Person(){
            this.colors = ["red","blue","green"];
        }        
        function Student(){
            Person.call(this);
        }
        var student1 = new Person();
        student1.colors.push("black");
        console.log(student1.colors);

        var student2 =new Person();
        console.log(student2.colors);
    通过构造函数继承,改变了原型继承的缺陷.
    可以看到这里继承了父类的引用类型值,但是子类的不同实例间没有相互影响
    同时,这样还可以在继承中向父类传递参数.
//典型的javascript继承:
    /*定义一个人类*/  
    function Person(name,age)  
    {  
        this.name=name;  
        this.age=age;
        this.property = true;                
     } 
        Person.prototype.getPersonValue = function(){
                return this.property;
        }                
    /*定义一个学生类*/  
    function Student(name,age,grade)  
    {                
        Student.call(this,name,age);           
        this.grade=grade; 
        this.subproperty = false;                       
    } 

        Student.prototype = Object.create(Student.prototype);;
        Student.prototype.constructor = Student;
        Student.prototype.getStudentValue = function(){
        return this.subproperty;
        };
        //创建一个学生类
        var student = new Student("chentao",24,"一年级");
        //测试
        console.log(student.getPersonValue());
        alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);                                                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值