构造函数,原型链的继承

构造函数

摘要:

  • 构造函数首字母大写(区分够着函数与普通函数)
  • 使用new关键词常见构造函数对象(与系统标准对象使用方法一致)
  • js的所有对象都有一个proto属性,调用方法obj.__ proto__
  • 只有函数有prototype属性,该属性是一个指针,指向一个对象,即对象原型(constructor

以下为代码演示:

    // function Student(name){
    //     this.name=name;
    //     this.hello=function(){
    //         alert("hello"+this.name);
    //     }
    // }     这种构造函数的写法会为每个obj对象创建一个hello()函数,增大内存负担
    
    function Student(props){
        this.name=props.name;
        this.grade=props.grade;
    }
    Student.prototype.hello=function(){
        alert("hello,"+this.name);
    }    //这样写把hello()加在了prototype上,每次调用的都是原型上的hello()方法

    function createStudent(props){
        return new Student(props || {})
    }   //封装的new函数:1、可以省去new定义,2、参数可以为空,这样多参数可以设置默认值,只传入我们需要的参数即可 
    //如果创建的对象有很多属性,我们只需要传递需要的某些属性,剩下的属性可以用默认值
复制代码

构造函数的原型链继承

摘要:JavaScript的原型继承实现方式

  • 定义构造函数
  • 内部调用call()调用继承的构造函数,并绑定this
  • 借助中间函数F,实现原型链的继承,封装inherits()函数
  • 继续在新的构造函数上定义新的方法

以下为代码演示:

    function Student(props){
        this.name=props.name || 'Unnamed';
    }
    Student.prototype.hello=function(){
        alert("hello,"+this.name)
    }
    
    function PrimaryStudent(props) {
        Student.call(this, props);
        this.grade = props.grade || 1;
    }    

    function inherits(Child, Parent) {
        var F = function () {};
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
    }

 
    // 实现原型继承链:
    inherits(PrimaryStudent, Student);

    // 绑定其他方法到PrimaryStudent原型:
    PrimaryStudent.prototype.getGrade = function () {
        return this.grade;
    };
复制代码

es-6新增class继承

直接上代码....

 class Student{
        constructor(name){
            this.name=name;
        }
        hello(){
            alert("hello,"+this.name)
        }
    }   //es6--class定义实现原型链的继承,与我们之前是一样的逻辑,只是封装了一下,写法不一样了

    class PrimaryStudent extends Student{
        constructor(name,grade){
            super(name);  //用super调用父类的构造方法 
            this.grade=grade;
        }
        myGrade(){
            alert("我的成绩:"+this.grade)
        }

    }

    var xiaoming=new Student("小明",90);
    var zhangsan=new PrimaryStudent("张三",80);
    var lisi=new PrimaryStudent("李四",99);

    xiaoming.hello();
    // xiaoming.myGrade();  报错
    zhangsan.myGrade();
    console.log(zhangsan.myGrade===lisi.myGrade);

复制代码

以上为自己学习总结,欢迎纠错。

转载于:https://juejin.im/post/5be8ea3c51882516ab6a858b

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值