构造器和原型(constructor & prototype)

2 篇文章 0 订阅
2 篇文章 0 订阅

                            构造器和原型(constructor & prototype)

其实构造器和原型是一个东西,constructor只不过是prototype的语法糖.只不过是不同ES版本不同的写法

下面举个例子哈:

function people(name,age){
        this.name = name;
        this.age = age;
    }
    people.prototype.say = function(language){
        console.log(this.name + ' is say ' + language);
    }

    // let people1 = new people('Alex',26);
    // people1.say('chinese');

    /*
    * 其上其实和下文的构造函数是一样的
    * */

    class peopleClass {
        constructor(name,age) {
            this.name = name;
            this.age = age;
            // console.log(name + age);
        }
        say(language){
            console.log(this.name + ' is say ' + language);
        }
    }

    // let peopleClass1 = new peopleClass('Alex',27);
    // peopleClass1.say('chinese');

    class peopleClass1 extends peopleClass{
        constructor(a, b) {
            super(a, b);//继承父类的属性和方法
            console.log(a,b);
        }
    }
    let Alex = new peopleClass1('Alex',28);
    Alex.say('chinese')
注意:
* 子类必须在constructor()中调用super()方法.否则新建实例时会报错.
 因为子类是没有自己的 this 对象的,它只能继承自父类的 this 对象,然后对其进行加工,
而super( )就是将父类中的this对象继承给子类的。没有 super,子类就得不到 this 对象,没有 this 对象 如果要使用this的话就会报错.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值