js中es5类的创建继承与es6中类的创建继承

js中es5类的创建继承与es6中类的创建继承

es5类的创建与继承

    console.log('寄生组合式继承');
// 生成一个类的方法
    function TheClass(props) {
        //绑定基础属性()
//        this.constructor=
        this.name=props.name||'';
        this.grade=props.grade||'';
    }
    //往原型链上绑定方法
    TheClass.prototype.hello=function () {
        alert('Hello'+this.name);
    };
//使用创建函数
    function createClass(props) {
        return new TheClass(props||{});
    }
    //使用原型继承
    function inherits(Child, Parent) {
        var F = function () {};
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
    }
//产生新的子class
    function TheClassChild(props) {
        TheClass.call(this,props);
        this.zzz=props.zzz||'';
    }
    //子类绑定父类
    inherits(TheClassChild,TheClass);
    TheClassChild.prototype.alertA=function () {
        alert(this.zzz);
    };
function createTheClassChild(props) {
    return new TheClassChild(props||{});
}
var bb=new TheClass({name:'baby',grade:'class1'});
bb.hello();
var cc=new TheClassChild({name:'baby',grade:'class1',zzz:'bbbb'});
cc.alertA();

es6+的class创建与继承

class Student2{
    constructor(props){
this.name=props.name||'';
    }
    hello(){
        alert(this.name);
    }
}
var s1=new Student2({name:'小张'});
s1.hello();
//继承
class PrimaryStudent2 extends Student2 {
    constructor(props) {
        super(props||{}); // 记得用super调用父类的构造方法!
        this.grade = props.grade||'';
    }

    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}
var s2=new PrimaryStudent2({name:'小王',grade:'yi'});

s2.myGrade();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值